diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..8af015e80f091250d212a93edc52de60aa81134e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/canaries/first-hunk-only.sh @@ -0,0 +1,29 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/error_store.py b/src/marshmallow/error_store.py +index 419d43eaa143bf995a9e3b497369ab3a7a30282d..72b703736428168885ab02a800d8f755cc4d3bf6 100644 +--- a/src/marshmallow/error_store.py ++++ b/src/marshmallow/error_store.py +@@ -15,11 +15,14 @@ + self.errors = {} + + def store_error(self, messages, field_name=SCHEMA, index=None): +- if field_name == SCHEMA and isinstance(messages, dict): +- messages = [messages] +- if index == 0: ++ # field error -> store/merge error messages under field name key ++ # schema error -> if string or list, store/merge under _schema key ++ # -> if dict, store/merge with other top-level keys ++ if field_name != SCHEMA or not isinstance(messages, dict): + messages = {field_name: messages} +- self.errors = merge_errors(messages, self.errors) ++ if index is not None: ++ messages = {index: messages} ++ self.errors = merge_errors(self.errors, messages) + + + def merge_errors(errors1, errors2): +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_file__x2xypft4/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..111ac2ea0bebab22e5fcabf103094bf18f05aaca --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "d2ab7394d572e23c97904cf70471c24c35009b73dce040ebfff8ceda350f30b8", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "eaa52c4db4ea58c622437d5befb7547b726810ea073054b3507c64eae4d6af4a", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "d78795aae0ce90809b13ed16ea2ab418ad91c855638e737c357dd2ea878b354f", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "5a0745a294404e1538c74004a906777bc1bb8395", + "source_completion_sha256": "3affac2a48e264ace97e82cd4ffb6d8c7c80c3ff01fe78f3cf551e9b65479c75", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "32dabd19844c79b576e2178cc05877ad4dabf48b3fab55dcc4a523675203f950", + "is_fork": true, + "learner_path": "tasks/a8f57446286292e84eae251f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/5a0745a294404e1538c74004a906777bc1bb8395/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "1582a7735b96db97d76648ac51722a14ecdb3128dcd16d9242635c2f31754d13", + "provenance_path": "tasks/a8f57446286292e84eae251f/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "5a0745a294404e1538c74004a906777bc1bb8395", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "30f880ddd089e15fc943c57c51b6cfb18d2781e7", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj", + "task_sha256": "9ff4532cb3a78a68a116dc7fc3fabebbdb578d28ad03e0e2502815b1fa7f622d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..171c07be19392560c42ad634eb3bc7fd29a69478 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/instruction.md @@ -0,0 +1,42 @@ +URL validation fails with UnboundLocalError + +#### Description + +URL validation is broken and raises `UnboundLocalError: local variable 'key' referenced before assignment` when trying to validate any URL. + +#### Steps/Code to Reproduce + +```python +from marshmallow import validate + +# This should work but raises UnboundLocalError +validator = validate.URL() +validator('http://example.org') +``` + +The error occurs for all URL validation scenarios: + +```python +from marshmallow import validate + +# All of these raise UnboundLocalError +validate.URL(relative=False)('http://example.org') +validate.URL(relative=True)('/foo/bar') +validate.URL(require_tld=False)('http://example') +``` + +#### Expected Behavior + +URL validation should work normally and either return the valid URL or raise a ValidationError for invalid URLs. + +#### Actual Behavior + +``` +UnboundLocalError: local variable 'key' referenced before assignment +``` + +This affects all URL validation functionality in the library. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..4eae699ebab66289e88ba1572949336f42fd5df5 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "30f880ddd089e15fc943c57c51b6cfb18d2781e7", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "5a0745a294404e1538c74004a906777bc1bb8395" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_decorators.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_deserialization.py", + "tests/test_options.py", + "tests/test_registry.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/class_registry.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2198857, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "32dabd19844c79b576e2178cc05877ad4dabf48b3fab55dcc4a523675203f950", + "is_fork": true, + "learner_path": "tasks/a8f57446286292e84eae251f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/5a0745a294404e1538c74004a906777bc1bb8395/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "1582a7735b96db97d76648ac51722a14ecdb3128dcd16d9242635c2f31754d13", + "provenance_path": "tasks/a8f57446286292e84eae251f/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "5a0745a294404e1538c74004a906777bc1bb8395", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "30f880ddd089e15fc943c57c51b6cfb18d2781e7", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj", + "task_sha256": "9ff4532cb3a78a68a116dc7fc3fabebbdb578d28ad03e0e2502815b1fa7f622d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..1d90fda768422eb22ecf883f402c5995c2d9ab86 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "d2ab7394d572e23c97904cf70471c24c35009b73dce040ebfff8ceda350f30b8", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/5a0745a294404e1538c74004a906777bc1bb8395/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "3affac2a48e264ace97e82cd4ffb6d8c7c80c3ff01fe78f3cf551e9b65479c75", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "4b69b13ddb8eff4c8a6c8ff5d5f293ff055aa62f617b223f59bb2a0718ca535f", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "32dabd19844c79b576e2178cc05877ad4dabf48b3fab55dcc4a523675203f950", + "is_fork": true, + "learner_path": "tasks/a8f57446286292e84eae251f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/5a0745a294404e1538c74004a906777bc1bb8395/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "1582a7735b96db97d76648ac51722a14ecdb3128dcd16d9242635c2f31754d13", + "provenance_path": "tasks/a8f57446286292e84eae251f/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "5a0745a294404e1538c74004a906777bc1bb8395", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "30f880ddd089e15fc943c57c51b6cfb18d2781e7", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj", + "task_sha256": "9ff4532cb3a78a68a116dc7fc3fabebbdb578d28ad03e0e2502815b1fa7f622d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..f4f48aad12af1377a8c3632d580ace51daffeb8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/provided-gold.diff @@ -0,0 +1,47 @@ +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index 1ff1b0db351cf1554b8b1563be1ca3dc97d944e0..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -77,17 +77,18 @@ + """ + try: + classes = _registry[classname] +- except KeyError: ++ except KeyError as error: + raise RegistryError( + f"Class with name {classname!r} was not found. You may need " + "to import the class." +- ) ++ ) from error + if len(classes) > 1: +- if not all: ++ if all: + return _registry[classname] + raise RegistryError( + f"Multiple classes with name {classname!r} " + "were found. Please use the full, " + "module-qualified path." + ) +- return classes[-1] ++ else: ++ return _registry[classname][0] +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index ce2430180eeaf81ee3f6d01318957fe936d857d9..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -163,13 +163,14 @@ + def __call__( + self, relative: bool, absolute: bool, require_tld: bool + ) -> typing.Pattern: ++ key = (relative, absolute, require_tld) + if key not in self._memoized: + self._memoized[key] = self._regex_generator( + relative, absolute, require_tld + ) + + return self._memoized[key] +- key = (relative, absolute, require_tld) ++ + _regex = RegexMemoizer() + + default_message = "Not a valid URL." diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e539de2b005984e1c8b4a77f28307ffec5ab86d2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/solution/solve.sh @@ -0,0 +1,53 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index 1ff1b0db351cf1554b8b1563be1ca3dc97d944e0..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -77,17 +77,18 @@ + """ + try: + classes = _registry[classname] +- except KeyError: ++ except KeyError as error: + raise RegistryError( + f"Class with name {classname!r} was not found. You may need " + "to import the class." +- ) ++ ) from error + if len(classes) > 1: +- if not all: ++ if all: + return _registry[classname] + raise RegistryError( + f"Multiple classes with name {classname!r} " + "were found. Please use the full, " + "module-qualified path." + ) +- return classes[-1] ++ else: ++ return _registry[classname][0] +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index ce2430180eeaf81ee3f6d01318957fe936d857d9..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -163,13 +163,14 @@ + def __call__( + self, relative: bool, absolute: bool, require_tld: bool + ) -> typing.Pattern: ++ key = (relative, absolute, require_tld) + if key not in self._memoized: + self._memoized[key] = self._regex_generator( + relative, absolute, require_tld + ) + + return self._memoized[key] +- key = (relative, absolute, require_tld) ++ + _regex = RegexMemoizer() + + default_message = "Not a valid URL." +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4fefdcc01227a330c517290c28731b73ce10f77a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:ab70e635aa170a8051895226654b82557a5125f5aa0de1d671c45d7427e45ad3" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..2c3bf4b7c625fdc1a4e26e60bd0797032a7dc396 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..b6793a1937509752ab6d54eda5120578f984a835 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/validation/canaries/first-hunk-only.sh @@ -0,0 +1,33 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index 1ff1b0db351cf1554b8b1563be1ca3dc97d944e0..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -77,17 +77,18 @@ + """ + try: + classes = _registry[classname] +- except KeyError: ++ except KeyError as error: + raise RegistryError( + f"Class with name {classname!r} was not found. You may need " + "to import the class." +- ) ++ ) from error + if len(classes) > 1: +- if not all: ++ if all: + return _registry[classname] + raise RegistryError( + f"Multiple classes with name {classname!r} " + "were found. Please use the full, " + "module-qualified path." + ) +- return classes[-1] ++ else: ++ return _registry[classname][0] +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__1wlcf7hj/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..a447e9528cf3412bec9aa66ed6a69c8ef22059d6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "0405a3140a95b0c604ae09c5592ac2bd724af806c157b4ed54c54ef02ce3703d", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "6169bd6ec59f47eff1d67c9abb83a0c7d99c3e3561b86dbc8446c88e4cecea48", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "970bd3737bd20826a51acfe37ba9ba1f5b66d326415c48cb85a4251b62793026", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "d4cfb48165daae35f455d5cd3339dc5d41a2b306", + "source_completion_sha256": "84fad7b107a62f998b36a502ff1cf4a84926379d7d1ec029e45c9c7f47275fde", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "a82aff1b44282ab38287c67c8536056f864fd25f69e7d3c3cc49b2eabe9168be", + "is_fork": true, + "learner_path": "tasks/511f9157b230ebfe11338ba7/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/d4cfb48165daae35f455d5cd3339dc5d41a2b306/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "c001441e46db8af64f7eb56b124131c7d42b1f4b8b95c2690f93be2705c25547", + "provenance_path": "tasks/511f9157b230ebfe11338ba7/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d4cfb48165daae35f455d5cd3339dc5d41a2b306", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "be9897ba4dfb1743353466652fbdae9e52a93329", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1", + "task_sha256": "cfa2fd9b2b7a6b755b3d8b0e9d39576de30977c84463c533df96915d15761f5d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bdf255478ee4575ffc9e3c27fa79e02270c17b52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/instruction.md @@ -0,0 +1,49 @@ +OneOf validator incorrectly rejects valid values + +#### Description + +The OneOf validator is rejecting values that should be valid. When a value is in the choices list, it raises a ValidationError instead of accepting it. + +#### Steps/Code to Reproduce + +```python +from marshmallow import validate + +# This should pass but raises ValidationError +validator = validate.OneOf([1, 2, 3]) +try: + result = validator(2) # 2 is in the choices, should be valid + print(f"Result: {result}") +except Exception as e: + print(f"Error: {e}") + +# Custom message test - this should raise but doesn't +validator_custom = validate.OneOf([1, 2, 3], error="Custom error message") +try: + result = validator_custom(5) # 5 is not in choices, should raise + print(f"Unexpected success: {result}") +except Exception as e: + print(f"Expected error: {e}") +``` + +Also affects ContainsOnly validator which returns truncated results: + +```python +from marshmallow import validate + +# This should return the full list but returns truncated +validator = validate.ContainsOnly([1, 2, 3]) +result = validator([1]) +print(f"Expected: [1], Got: {result}") + +# With unhashable types +validator_unhashable = validate.ContainsOnly([[1], [2], [3]]) +result = validator_unhashable([[1]]) +print(f"Expected: [[1]], Got: {result}") +``` + +The validators are behaving opposite to their intended logic - OneOf accepts invalid values and rejects valid ones, while ContainsOnly returns modified/truncated input instead of the original. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..d9f8e04e2de1997fba0854d3b2b1232a71d4d733 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "be9897ba4dfb1743353466652fbdae9e52a93329", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "d4cfb48165daae35f455d5cd3339dc5d41a2b306" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_decorators.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_deserialization.py", + "tests/test_registry.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/class_registry.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2204975, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "a82aff1b44282ab38287c67c8536056f864fd25f69e7d3c3cc49b2eabe9168be", + "is_fork": true, + "learner_path": "tasks/511f9157b230ebfe11338ba7/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/d4cfb48165daae35f455d5cd3339dc5d41a2b306/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "c001441e46db8af64f7eb56b124131c7d42b1f4b8b95c2690f93be2705c25547", + "provenance_path": "tasks/511f9157b230ebfe11338ba7/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d4cfb48165daae35f455d5cd3339dc5d41a2b306", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "be9897ba4dfb1743353466652fbdae9e52a93329", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1", + "task_sha256": "cfa2fd9b2b7a6b755b3d8b0e9d39576de30977c84463c533df96915d15761f5d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..72566287050f2617cea671473da53722e877bc1c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "0405a3140a95b0c604ae09c5592ac2bd724af806c157b4ed54c54ef02ce3703d", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/d4cfb48165daae35f455d5cd3339dc5d41a2b306/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "84fad7b107a62f998b36a502ff1cf4a84926379d7d1ec029e45c9c7f47275fde", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "c175c7cc182a3f9f0501749e74adf2aaaa5a9c47e9aed921dbaa3974e344e9bc", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "a82aff1b44282ab38287c67c8536056f864fd25f69e7d3c3cc49b2eabe9168be", + "is_fork": true, + "learner_path": "tasks/511f9157b230ebfe11338ba7/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/d4cfb48165daae35f455d5cd3339dc5d41a2b306/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "c001441e46db8af64f7eb56b124131c7d42b1f4b8b95c2690f93be2705c25547", + "provenance_path": "tasks/511f9157b230ebfe11338ba7/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d4cfb48165daae35f455d5cd3339dc5d41a2b306", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "be9897ba4dfb1743353466652fbdae9e52a93329", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1", + "task_sha256": "cfa2fd9b2b7a6b755b3d8b0e9d39576de30977c84463c533df96915d15761f5d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..fa5ebe0d6b128448ab50e4bd7f514e2abe5d3803 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/provided-gold.diff @@ -0,0 +1,108 @@ +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index 076327dc7c03539d75f31468f9a27f2236e92183..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -27,20 +27,45 @@ + + + def register(classname: str, cls: SchemaType) -> None: ++ """Add a class to the registry of serializer classes. When a class is ++ registered, an entry for both its classname and its full, module-qualified ++ path are added to the registry. ++ ++ Example: :: ++ ++ class MyClass: ++ pass ++ ++ ++ register("MyClass", MyClass) ++ # Registry: ++ # { ++ # 'MyClass': [path.to.MyClass], ++ # 'path.to.MyClass': [path.to.MyClass], ++ # } ++ ++ """ ++ # Module where the class is located + module = cls.__module__ ++ # Full module path to the class ++ # e.g. user.schemas.UserSchema + fullpath = ".".join([module, classname]) +- +- if classname in _registry and any( ++ # If the class is already registered; need to check if the entries are ++ # in the same module as cls to avoid having multiple instances of the same ++ # class in the registry ++ if classname in _registry and not any( + each.__module__ == module for each in _registry[classname] + ): +- del _registry[classname] ++ _registry[classname].append(cls) + elif classname not in _registry: + _registry[classname] = [cls] + ++ # Also register the full path + if fullpath not in _registry: ++ _registry.setdefault(fullpath, []).append(cls) ++ else: ++ # If fullpath does exist, replace existing entry + _registry[fullpath] = [cls] +- else: +- _registry[fullpath].append(cls) + return None + + +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 39abd15c6ffc7bb7401f278c2e79a611d5d5dd67..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -163,12 +163,12 @@ + def __call__( + self, relative: bool, absolute: bool, require_tld: bool + ) -> typing.Pattern: +- key = (absolute, relative, require_tld) ++ key = (relative, absolute, require_tld) + if key not in self._memoized: + self._memoized[key] = self._regex_generator( +- relative, absolute, not require_tld ++ relative, absolute, require_tld + ) +- ++ + return self._memoized[key] + + _regex = RegexMemoizer() +@@ -597,12 +597,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value in self.choices: ++ if value not in self.choices: + raise ValidationError(self._format_error(value)) +- except TypeError: +- pass +- +- return None ++ except TypeError as error: ++ raise ValidationError(self._format_error(value)) from error ++ ++ return value + + def options( + self, +@@ -647,11 +647,11 @@ + return super()._format_error(value_text) + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: +- reversed_choices = list(reversed(self.choices)) ++ # We can't use set.issubset because does not handle unhashable types + for val in value: +- if val not in reversed_choices: ++ if val not in self.choices: + raise ValidationError(self._format_error(value)) +- return value[:-1] ++ return value + + + class ContainsNoneOf(NoneOf): diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2fe6897838156e0bb411649406bde99008e1f1db --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/solution/solve.sh @@ -0,0 +1,114 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index 076327dc7c03539d75f31468f9a27f2236e92183..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -27,20 +27,45 @@ + + + def register(classname: str, cls: SchemaType) -> None: ++ """Add a class to the registry of serializer classes. When a class is ++ registered, an entry for both its classname and its full, module-qualified ++ path are added to the registry. ++ ++ Example: :: ++ ++ class MyClass: ++ pass ++ ++ ++ register("MyClass", MyClass) ++ # Registry: ++ # { ++ # 'MyClass': [path.to.MyClass], ++ # 'path.to.MyClass': [path.to.MyClass], ++ # } ++ ++ """ ++ # Module where the class is located + module = cls.__module__ ++ # Full module path to the class ++ # e.g. user.schemas.UserSchema + fullpath = ".".join([module, classname]) +- +- if classname in _registry and any( ++ # If the class is already registered; need to check if the entries are ++ # in the same module as cls to avoid having multiple instances of the same ++ # class in the registry ++ if classname in _registry and not any( + each.__module__ == module for each in _registry[classname] + ): +- del _registry[classname] ++ _registry[classname].append(cls) + elif classname not in _registry: + _registry[classname] = [cls] + ++ # Also register the full path + if fullpath not in _registry: ++ _registry.setdefault(fullpath, []).append(cls) ++ else: ++ # If fullpath does exist, replace existing entry + _registry[fullpath] = [cls] +- else: +- _registry[fullpath].append(cls) + return None + + +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 39abd15c6ffc7bb7401f278c2e79a611d5d5dd67..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -163,12 +163,12 @@ + def __call__( + self, relative: bool, absolute: bool, require_tld: bool + ) -> typing.Pattern: +- key = (absolute, relative, require_tld) ++ key = (relative, absolute, require_tld) + if key not in self._memoized: + self._memoized[key] = self._regex_generator( +- relative, absolute, not require_tld ++ relative, absolute, require_tld + ) +- ++ + return self._memoized[key] + + _regex = RegexMemoizer() +@@ -597,12 +597,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value in self.choices: ++ if value not in self.choices: + raise ValidationError(self._format_error(value)) +- except TypeError: +- pass +- +- return None ++ except TypeError as error: ++ raise ValidationError(self._format_error(value)) from error ++ ++ return value + + def options( + self, +@@ -647,11 +647,11 @@ + return super()._format_error(value_text) + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: +- reversed_choices = list(reversed(self.choices)) ++ # We can't use set.issubset because does not handle unhashable types + for val in value: +- if val not in reversed_choices: ++ if val not in self.choices: + raise ValidationError(self._format_error(value)) +- return value[:-1] ++ return value + + + class ContainsNoneOf(NoneOf): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2a0a7122d81a32a4467ea5eee44a4e386fbbc6b0 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:998c611b70c328e42391495b01caaa4a4474231e6b6d6b2270e7f1c947512546" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..8d06e66617f7d55101c279ff4dc48b4002a3891b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..5ac65126c5106d3ec96777594516d370492f9d7e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/validation/canaries/first-hunk-only.sh @@ -0,0 +1,61 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index 076327dc7c03539d75f31468f9a27f2236e92183..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -27,20 +27,45 @@ + + + def register(classname: str, cls: SchemaType) -> None: ++ """Add a class to the registry of serializer classes. When a class is ++ registered, an entry for both its classname and its full, module-qualified ++ path are added to the registry. ++ ++ Example: :: ++ ++ class MyClass: ++ pass ++ ++ ++ register("MyClass", MyClass) ++ # Registry: ++ # { ++ # 'MyClass': [path.to.MyClass], ++ # 'path.to.MyClass': [path.to.MyClass], ++ # } ++ ++ """ ++ # Module where the class is located + module = cls.__module__ ++ # Full module path to the class ++ # e.g. user.schemas.UserSchema + fullpath = ".".join([module, classname]) +- +- if classname in _registry and any( ++ # If the class is already registered; need to check if the entries are ++ # in the same module as cls to avoid having multiple instances of the same ++ # class in the registry ++ if classname in _registry and not any( + each.__module__ == module for each in _registry[classname] + ): +- del _registry[classname] ++ _registry[classname].append(cls) + elif classname not in _registry: + _registry[classname] = [cls] + ++ # Also register the full path + if fullpath not in _registry: ++ _registry.setdefault(fullpath, []).append(cls) ++ else: ++ # If fullpath does exist, replace existing entry + _registry[fullpath] = [cls] +- else: +- _registry[fullpath].append(cls) + return None + + +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__a0zj7oz1/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..5a550ae80084300b10b168f99bcc236ba42444eb --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "def6636da0adfb929abc82d5b10d0585a3b23e5ab4da88aa7bed7043f3c0e0c8", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "1f2cb25997567a17710bbd187258f19dfd5a9f66e343c3c7e45a87063c3275cf", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "49f10895765695fc6aa22883618522ea9ce6be04f9879970f9ded30a34632532", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "ac1fdf7a043bdda97b1519b5c75d90c3e42dd44f", + "source_completion_sha256": "8f25342db2a30113254a8d0a810834cf12a670867583b7d2801800324c77eba8", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "ef494bea762cc083810364eaa73ae549ee39f2be50ae1f069ae8b2faacacd97a", + "is_fork": true, + "learner_path": "tasks/08414153824aaa507b9caa53/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ac1fdf7a043bdda97b1519b5c75d90c3e42dd44f/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "6590bc78aca5137865d3c08fcf1df689f15c1938f8d43e8e70b29bbfac49a347", + "provenance_path": "tasks/08414153824aaa507b9caa53/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ac1fdf7a043bdda97b1519b5c75d90c3e42dd44f", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "c4590549673eda75fd9f3d2936600294f09b2465", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz", + "task_sha256": "1d7bd32bdad24dc6b3d39bd2fc8b4a076cbd331fbce542ab97b4831c74a6bc03", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8b9c15f19f0691e64176a0ed60df91ca720bb6dd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/instruction.md @@ -0,0 +1,45 @@ +OrderedSet equality comparison broken + +#### Description + +OrderedSet equality comparison is not working correctly. When comparing two OrderedSet instances, the comparison always returns False even when they contain the same elements in the same order. + +#### Steps/Code to Reproduce + +```python +from marshmallow.orderedset import OrderedSet + +# Create two identical OrderedSets +set1 = OrderedSet(['a', 'b', 'c']) +set2 = OrderedSet(['a', 'b', 'c']) + +print(f"set1 == set2: {set1 == set2}") # Should be True but returns False +print(f"set1: {set1}") +print(f"set2: {set2}") + +# Also affects comparison with regular sets +regular_set = {'a', 'b', 'c'} +print(f"set1 == regular_set: {set1 == regular_set}") # Should be True but returns False +``` + +Expected output: +``` +set1 == set2: True +set1: OrderedSet(['a', 'b', 'c']) +set2: OrderedSet(['a', 'b', 'c']) +set1 == regular_set: True +``` + +Actual output: +``` +set1 == set2: False +set1: OrderedSet(['a', 'b', 'c']) +set2: OrderedSet(['a', 'b', 'c']) +set1 == regular_set: False +``` + +This breaks schema field comparisons and other functionality that relies on OrderedSet equality. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..22d652d861fae849c7699b25dc8efb4eb29db54c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_and" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "c4590549673eda75fd9f3d2936600294f09b2465", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "ac1fdf7a043bdda97b1519b5c75d90c3e42dd44f" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_decorators.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_schema.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_deserialization.py", + "tests/test_fields.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/orderedset.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2281924, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "ef494bea762cc083810364eaa73ae549ee39f2be50ae1f069ae8b2faacacd97a", + "is_fork": true, + "learner_path": "tasks/08414153824aaa507b9caa53/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ac1fdf7a043bdda97b1519b5c75d90c3e42dd44f/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "6590bc78aca5137865d3c08fcf1df689f15c1938f8d43e8e70b29bbfac49a347", + "provenance_path": "tasks/08414153824aaa507b9caa53/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ac1fdf7a043bdda97b1519b5c75d90c3e42dd44f", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "c4590549673eda75fd9f3d2936600294f09b2465", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz", + "task_sha256": "1d7bd32bdad24dc6b3d39bd2fc8b4a076cbd331fbce542ab97b4831c74a6bc03", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..1f76c47c3bd27caeb26d4dc4ef3697a8f3d1693a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "def6636da0adfb929abc82d5b10d0585a3b23e5ab4da88aa7bed7043f3c0e0c8", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ac1fdf7a043bdda97b1519b5c75d90c3e42dd44f/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "8f25342db2a30113254a8d0a810834cf12a670867583b7d2801800324c77eba8", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "1e07d912cfb2753a42ad20e67e903225cee0aeb91f010b8b75f5bcf705db9c6a", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "ef494bea762cc083810364eaa73ae549ee39f2be50ae1f069ae8b2faacacd97a", + "is_fork": true, + "learner_path": "tasks/08414153824aaa507b9caa53/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ac1fdf7a043bdda97b1519b5c75d90c3e42dd44f/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "6590bc78aca5137865d3c08fcf1df689f15c1938f8d43e8e70b29bbfac49a347", + "provenance_path": "tasks/08414153824aaa507b9caa53/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ac1fdf7a043bdda97b1519b5c75d90c3e42dd44f", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "c4590549673eda75fd9f3d2936600294f09b2465", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz", + "task_sha256": "1d7bd32bdad24dc6b3d39bd2fc8b4a076cbd331fbce542ab97b4831c74a6bc03", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..5f9fe5f5610795b69787bc0184083b55911474de --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/provided-gold.diff @@ -0,0 +1,28 @@ +diff --git a/src/marshmallow/orderedset.py b/src/marshmallow/orderedset.py +index 959ff79ca29637fe3f2b26474d0f5a1402504ada..7ce0723ac42d747071755d9339c953f4669a0976 100644 +--- a/src/marshmallow/orderedset.py ++++ b/src/marshmallow/orderedset.py +@@ -77,8 +77,8 @@ + + def __eq__(self, other): + if isinstance(other, OrderedSet): +- return len(self) == len(other) and self != other +- return set(self) != set(other) ++ return len(self) == len(other) and list(self) == list(other) ++ return set(self) == set(other) + + + if __name__ == "__main__": +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index eeffcb910d106f0e5d737d04ff3bf779579ce4b5..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -339,7 +339,7 @@ + return f"min={self.min!r}, max={self.max!r}, min_inclusive={self.min_inclusive!r}, max_inclusive={self.max_inclusive!r}" + + def _format_error(self, value: _T, message: str) -> str: +- return (self.error and message).format(input=value, min=self.max, max=self.min) ++ return (self.error or message).format(input=value, min=self.min, max=self.max) + + def __call__(self, value: _T) -> _T: + if self.min is not None and ( diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b4290e0ca840b148e75e4e38d8f5e75720be5fd8 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/solution/solve.sh @@ -0,0 +1,34 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/orderedset.py b/src/marshmallow/orderedset.py +index 959ff79ca29637fe3f2b26474d0f5a1402504ada..7ce0723ac42d747071755d9339c953f4669a0976 100644 +--- a/src/marshmallow/orderedset.py ++++ b/src/marshmallow/orderedset.py +@@ -77,8 +77,8 @@ + + def __eq__(self, other): + if isinstance(other, OrderedSet): +- return len(self) == len(other) and self != other +- return set(self) != set(other) ++ return len(self) == len(other) and list(self) == list(other) ++ return set(self) == set(other) + + + if __name__ == "__main__": +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index eeffcb910d106f0e5d737d04ff3bf779579ce4b5..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -339,7 +339,7 @@ + return f"min={self.min!r}, max={self.max!r}, min_inclusive={self.min_inclusive!r}, max_inclusive={self.max_inclusive!r}" + + def _format_error(self, value: _T, message: str) -> str: +- return (self.error and message).format(input=value, min=self.max, max=self.min) ++ return (self.error or message).format(input=value, min=self.min, max=self.max) + + def __call__(self, value: _T) -> _T: + if self.min is not None and ( +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fa54e37d1f8b090c9e9ec097316f6f0090a8a84e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:9a174fd155182728c432332b19b02d45d33759745a5d0d1b7f9738973a497cf3" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..6a6785f2cecc9a63b2a47e19d9a0d3707eed05ad --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_and" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..ea35760c94165fa96303baac90fd9792f12088bb --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/validation/canaries/first-hunk-only.sh @@ -0,0 +1,21 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/orderedset.py b/src/marshmallow/orderedset.py +index 959ff79ca29637fe3f2b26474d0f5a1402504ada..7ce0723ac42d747071755d9339c953f4669a0976 100644 +--- a/src/marshmallow/orderedset.py ++++ b/src/marshmallow/orderedset.py +@@ -77,8 +77,8 @@ + + def __eq__(self, other): + if isinstance(other, OrderedSet): +- return len(self) == len(other) and self != other +- return set(self) != set(other) ++ return len(self) == len(other) and list(self) == list(other) ++ return set(self) == set(other) + + + if __name__ == "__main__": +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__apsh1edz/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..0fd5363674d3ee9a5c6d8a6daaa88e35b452cb15 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "8b7dd1c9e73b013f625c3a3cee9c2fc8388429bc0d39bcf0cbe6c9f70eeecc5f", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "4764addbeab1397a4988bd7262ebeb517fcf816725e71d52b62c581611430825", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "f04fc91b13b029620c0cada8a648f82aed83fee17d50c3f958c51e270d769619", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "e6883a8649d7bc647f599401bbbd499b9d4169c1", + "source_completion_sha256": "4c99e69387e09b63dc9e9c7bc2fde4bd12b24d48cf0ec81ca746aafbffeb8a22", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "5b68006886c0b6ed51c36f1e3c555f62b47ece5410bbf93e21b5d28a6c24a3c2", + "is_fork": true, + "learner_path": "tasks/8f6c626ad8bb1195ab38529c/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e6883a8649d7bc647f599401bbbd499b9d4169c1/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "153b0945ab446caa1f48583f986f9a81636acdc9a2a7af010fba042471d50424", + "provenance_path": "tasks/8f6c626ad8bb1195ab38529c/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e6883a8649d7bc647f599401bbbd499b9d4169c1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "01a7f5971fb0d1889342ab7a12453d122ac5eb82", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1", + "task_sha256": "1218f3c005e6c3475eabfc08ee55ad539cdebec6074518da70c18a6bd14585c6", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f8ad4876794f3ff3caeaaf325e2b3a30cfd1dc75 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/instruction.md @@ -0,0 +1,59 @@ +# Two issues with marshmallow decorators and ContainsOnly validator + +## Issue 1: Decorators `pre_dump` and `pre_load` not working correctly with `pass_many` parameter + +When using the `pre_dump` and `pre_load` decorators with the `pass_many` parameter, they behave opposite to what's expected. The `pass_many` parameter seems to be inverted, causing errors when processing data. + +### Steps to reproduce: + +```python +from marshmallow import Schema, fields, pre_dump, pre_load, post_dump, post_load + +class ExampleSchema(Schema): + TAG = 'TAG' + value = fields.Integer(as_string=True) + + @pre_dump + def increment_value(self, item, **kwargs): + # This fails because 'many' is not correctly passed + item['value'] += 1 + return item + + @pre_load(pass_many=True) + def remove_envelope(self, data, many, **kwargs): + # This fails because the 'many' parameter is inverted + key = 'data' if many else 'datum' + return data[key] + +schema = ExampleSchema() +item = {'value': 3} +schema.dump(item) # Raises KeyError: 'value' +``` + +### Expected behavior: +The decorators should correctly respect the `pass_many` parameter and process the data accordingly. + +## Issue 2: ContainsOnly validator truncates validated sequences + +The `ContainsOnly` validator is not only validating sequences but also modifying them by removing the last element. + +### Steps to reproduce: + +```python +from marshmallow.validate import ContainsOnly + +# Should return the original list +result = ContainsOnly([1, 2, 3])([1, 2]) +print(result) # Outputs: [] instead of [1, 2] + +# Should return the original string +result = ContainsOnly('abc')('a') +print(result) # Outputs: '' instead of 'a' +``` + +### Expected behavior: +The validator should only validate that all elements in the sequence are in the allowed choices, without modifying the sequence itself. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..8ff2d4ddede956b9064267527b9db2dad0b24bc4 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "01a7f5971fb0d1889342ab7a12453d122ac5eb82", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "e6883a8649d7bc647f599401bbbd499b9d4169c1" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_deserialization.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_schema.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/decorators.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2363707, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "5b68006886c0b6ed51c36f1e3c555f62b47ece5410bbf93e21b5d28a6c24a3c2", + "is_fork": true, + "learner_path": "tasks/8f6c626ad8bb1195ab38529c/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e6883a8649d7bc647f599401bbbd499b9d4169c1/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "153b0945ab446caa1f48583f986f9a81636acdc9a2a7af010fba042471d50424", + "provenance_path": "tasks/8f6c626ad8bb1195ab38529c/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e6883a8649d7bc647f599401bbbd499b9d4169c1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "01a7f5971fb0d1889342ab7a12453d122ac5eb82", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1", + "task_sha256": "1218f3c005e6c3475eabfc08ee55ad539cdebec6074518da70c18a6bd14585c6", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..0c75da392fad9693b67302cd041ea13cd418b95f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "8b7dd1c9e73b013f625c3a3cee9c2fc8388429bc0d39bcf0cbe6c9f70eeecc5f", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e6883a8649d7bc647f599401bbbd499b9d4169c1/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "4c99e69387e09b63dc9e9c7bc2fde4bd12b24d48cf0ec81ca746aafbffeb8a22", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "f6906448fed354881b3402554259dfeecb06247c99969ec886b2e46856b14510", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "5b68006886c0b6ed51c36f1e3c555f62b47ece5410bbf93e21b5d28a6c24a3c2", + "is_fork": true, + "learner_path": "tasks/8f6c626ad8bb1195ab38529c/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e6883a8649d7bc647f599401bbbd499b9d4169c1/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "153b0945ab446caa1f48583f986f9a81636acdc9a2a7af010fba042471d50424", + "provenance_path": "tasks/8f6c626ad8bb1195ab38529c/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e6883a8649d7bc647f599401bbbd499b9d4169c1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "01a7f5971fb0d1889342ab7a12453d122ac5eb82", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1", + "task_sha256": "1218f3c005e6c3475eabfc08ee55ad539cdebec6074518da70c18a6bd14585c6", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..e99dd8c9fd68ac45b66af28e0259af2769ead4e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/provided-gold.diff @@ -0,0 +1,41 @@ +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index a28d791a2b025919f6a61e6a9b7171d5b904052d..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +@@ -176,7 +176,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, PRE_LOAD, many=not pass_many) ++ return set_hook(fn, PRE_LOAD, many=pass_many) + + + def post_load( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index a51e9a73097e22fa24f7036f32e2f748f80791f5..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -647,11 +647,11 @@ + return super()._format_error(value_text) + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: +- reversed_choices = list(reversed(self.choices)) ++ # We can't use set.issubset because does not handle unhashable types + for val in value: +- if val not in reversed_choices: ++ if val not in self.choices: + raise ValidationError(self._format_error(value)) +- return value[:-1] ++ return value + + + class ContainsNoneOf(NoneOf): diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c19c879b25c40af72f4202aa07167ae31ecc7091 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/solution/solve.sh @@ -0,0 +1,47 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index a28d791a2b025919f6a61e6a9b7171d5b904052d..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +@@ -176,7 +176,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, PRE_LOAD, many=not pass_many) ++ return set_hook(fn, PRE_LOAD, many=pass_many) + + + def post_load( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index a51e9a73097e22fa24f7036f32e2f748f80791f5..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -647,11 +647,11 @@ + return super()._format_error(value_text) + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: +- reversed_choices = list(reversed(self.choices)) ++ # We can't use set.issubset because does not handle unhashable types + for val in value: +- if val not in reversed_choices: ++ if val not in self.choices: + raise ValidationError(self._format_error(value)) +- return value[:-1] ++ return value + + + class ContainsNoneOf(NoneOf): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f4fd272a185ec9263af48cc089db0cc206c961d8 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:d04c60c41af5ad15e75a831408a6cfc17d88efb72a7eddbc5b3f2ffa74d4c55d" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..708fb504316d578f80ecea89d8b6bd72ef39b43e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..aee50db50ca6373ffe746818305a13b92db81a9e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index a28d791a2b025919f6a61e6a9b7171d5b904052d..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__dp2codi1/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..4917e362ef3a37598cef8c29f4f36ae4e6c7b6e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "d4aa77db44ad3f0c157347791516b24004618f712a197125a27cbdfeaa477f5d", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "8a566202cb653f41bbed756f1e19830eb026f887dff6565ce16ca7eaca80c44f", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "6a1e3920a6a9a52d5560fa7be3b5e41415c628b9bcb5dfae70aaee89b392ceb3", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "7ed2bdaf170f0a52e91206bbd126353e95f68bb2", + "source_completion_sha256": "9fc7a8882146086d729925e4d603ba17f19892a66d825a804329c52c5131d8e8", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "8f8230ac3af525ba06f4c19e704dcdef80a7570aa3553b97c4030d27da61d5c7", + "is_fork": true, + "learner_path": "tasks/1ab23f2774fb5bf987e34411/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/7ed2bdaf170f0a52e91206bbd126353e95f68bb2/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "800804e3e44631658f69b0a62803d85c65470e05d2d36e11921bbf47e9297fb5", + "provenance_path": "tasks/1ab23f2774fb5bf987e34411/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "7ed2bdaf170f0a52e91206bbd126353e95f68bb2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ef23a052a4bcb43589edb78c0ab8fdea775678a7", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox", + "task_sha256": "9732142d8c5215499791495678d8dd2e65c18180db9dbf68fb74dd2205f959cf", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..33297d5fb9e68d6f75918a363ec9d729d4198c2e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/instruction.md @@ -0,0 +1,30 @@ +Field validation decorators not working correctly + +I'm having issues with field validation in marshmallow. When I use the `@validates` decorator, it seems like the field name is getting mangled somehow. + +Here's a simple example that should work but doesn't: + +```python +from marshmallow import Schema, fields, validates, ValidationError + +class TestSchema(Schema): + foo = fields.String() + + @validates('foo') + def validate_foo(self, value): + if value == 'bad': + raise ValidationError('Value cannot be bad') + +schema = TestSchema() +schema.validate({'foo': 'test'}) # This should work fine +``` + +Instead of working normally, I'm getting errors like `"oof" field does not exist.` when I try to validate the `foo` field. It's like the field name is being reversed or something weird. + +Also having problems with the `many=True` parameter in various decorators - seems like it's getting inverted. When I set `pass_many=True` in my pre_load/post_load decorators, the `many` parameter that gets passed to my method is `False` instead of `True`. + +And URL validation with `require_tld=False` is also broken - URLs that should be valid are being rejected. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..058bd4b62eb8f88efe2ceed6ceb23629a0325631 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "ef23a052a4bcb43589edb78c0ab8fdea775678a7", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "7ed2bdaf170f0a52e91206bbd126353e95f68bb2" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_deserialization.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/decorators.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2270945, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "8f8230ac3af525ba06f4c19e704dcdef80a7570aa3553b97c4030d27da61d5c7", + "is_fork": true, + "learner_path": "tasks/1ab23f2774fb5bf987e34411/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/7ed2bdaf170f0a52e91206bbd126353e95f68bb2/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "800804e3e44631658f69b0a62803d85c65470e05d2d36e11921bbf47e9297fb5", + "provenance_path": "tasks/1ab23f2774fb5bf987e34411/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "7ed2bdaf170f0a52e91206bbd126353e95f68bb2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ef23a052a4bcb43589edb78c0ab8fdea775678a7", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox", + "task_sha256": "9732142d8c5215499791495678d8dd2e65c18180db9dbf68fb74dd2205f959cf", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..8b0dd52dd84d5aabe7e68f070ce54ec8c36beac1 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "d4aa77db44ad3f0c157347791516b24004618f712a197125a27cbdfeaa477f5d", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/7ed2bdaf170f0a52e91206bbd126353e95f68bb2/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "9fc7a8882146086d729925e4d603ba17f19892a66d825a804329c52c5131d8e8", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "53038a45b737809b019af2938dd22885c23522ceb82d22622916fc6447f55600", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "8f8230ac3af525ba06f4c19e704dcdef80a7570aa3553b97c4030d27da61d5c7", + "is_fork": true, + "learner_path": "tasks/1ab23f2774fb5bf987e34411/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/7ed2bdaf170f0a52e91206bbd126353e95f68bb2/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "800804e3e44631658f69b0a62803d85c65470e05d2d36e11921bbf47e9297fb5", + "provenance_path": "tasks/1ab23f2774fb5bf987e34411/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "7ed2bdaf170f0a52e91206bbd126353e95f68bb2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ef23a052a4bcb43589edb78c0ab8fdea775678a7", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox", + "task_sha256": "9732142d8c5215499791495678d8dd2e65c18180db9dbf68fb74dd2205f959cf", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..9926feac4fddb9b925b5cbd5b48607f8c0bcaf87 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/provided-gold.diff @@ -0,0 +1,60 @@ +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index c439744b9c574370b5e1b07eae50686f3520779b..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -88,7 +88,7 @@ + + :param str field_name: Name of the field that the method validates. + """ +- return set_hook(None, VALIDATES, field_name=field_name[::-1]) ++ return set_hook(None, VALIDATES, field_name=field_name) + + + def validates_schema( +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +@@ -176,7 +176,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, PRE_LOAD, many=not pass_many) ++ return set_hook(fn, PRE_LOAD, many=pass_many) + + + def post_load( +@@ -198,7 +198,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, POST_LOAD, many=not pass_many, pass_original=pass_original) ++ return set_hook(fn, POST_LOAD, many=pass_many, pass_original=pass_original) + + + def set_hook( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 5371789c5c003252a55e12b7398061d9ced1eb9d..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -163,12 +163,12 @@ + def __call__( + self, relative: bool, absolute: bool, require_tld: bool + ) -> typing.Pattern: +- key = (absolute, relative, require_tld) ++ key = (relative, absolute, require_tld) + if key not in self._memoized: + self._memoized[key] = self._regex_generator( +- relative, absolute, not require_tld ++ relative, absolute, require_tld + ) +- ++ + return self._memoized[key] + + _regex = RegexMemoizer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2066ecba579761e615845483e98889bc7b9c4a3a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/solution/solve.sh @@ -0,0 +1,66 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index c439744b9c574370b5e1b07eae50686f3520779b..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -88,7 +88,7 @@ + + :param str field_name: Name of the field that the method validates. + """ +- return set_hook(None, VALIDATES, field_name=field_name[::-1]) ++ return set_hook(None, VALIDATES, field_name=field_name) + + + def validates_schema( +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +@@ -176,7 +176,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, PRE_LOAD, many=not pass_many) ++ return set_hook(fn, PRE_LOAD, many=pass_many) + + + def post_load( +@@ -198,7 +198,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, POST_LOAD, many=not pass_many, pass_original=pass_original) ++ return set_hook(fn, POST_LOAD, many=pass_many, pass_original=pass_original) + + + def set_hook( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 5371789c5c003252a55e12b7398061d9ced1eb9d..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -163,12 +163,12 @@ + def __call__( + self, relative: bool, absolute: bool, require_tld: bool + ) -> typing.Pattern: +- key = (absolute, relative, require_tld) ++ key = (relative, absolute, require_tld) + if key not in self._memoized: + self._memoized[key] = self._regex_generator( +- relative, absolute, not require_tld ++ relative, absolute, require_tld + ) +- ++ + return self._memoized[key] + + _regex = RegexMemoizer() +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..40d0672600f48e7c21a7975a23e6ebd52badf216 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:17f486992247c6e6c091d9dbf16e1327af9c1f16768d5f8e519f18b8389f9b73" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..5d8e77dbda425e570553c9f9b9db3099e2a8ff79 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..466096a90dec7a3d8db1e64532cb8ee5dece56af --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index c439744b9c574370b5e1b07eae50686f3520779b..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -88,7 +88,7 @@ + + :param str field_name: Name of the field that the method validates. + """ +- return set_hook(None, VALIDATES, field_name=field_name[::-1]) ++ return set_hook(None, VALIDATES, field_name=field_name) + + + def validates_schema( +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k1fz67ox/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..3848bdf0680daa4beb48a7bcc7ba2fce20016275 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "df6d3741de6897bfe23dbc087042d8ef1f88b59e779dddb443155fa99ac4a0a8", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "3752760b22ce7b7069dba2dbbc5babf6b2847157bf5d1bcb9a86236c0e67c851", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "1b2538ef6abc3bd26d8f37acbb753e621db1329480108c2b7dc5832ac600666f", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "4abe7a8e7890dfdecaa13a90e3961b540ac379ec", + "source_completion_sha256": "dfe641e0079845f7ed50366272c48baa20da16bee0e29c455039dbc49a2047e8", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "54e0d7e8e315313f044a2cecf8e0b9bc14c8b8d271bc74fa86cc7b2d79c110c5", + "is_fork": true, + "learner_path": "tasks/d417e5e6b41cfe915c13ce74/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/4abe7a8e7890dfdecaa13a90e3961b540ac379ec/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "1e352af0607fe009b72ce1f95e98bd20a7a948da9ae367f11d83a6a8a7a84259", + "provenance_path": "tasks/d417e5e6b41cfe915c13ce74/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "4abe7a8e7890dfdecaa13a90e3961b540ac379ec", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "df5cd7b4cc4b98932d871d0098c3d4882f1e3916", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc", + "task_sha256": "8c7e0a41cc8ac8f35e1732cef9226c99b665fdd705aa4f1c40a863e07e9b1d02", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e53280d09027325a0e9aaa6d028982048232d6c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/instruction.md @@ -0,0 +1,41 @@ +URL validation logic inverted - valid URLs rejected, invalid URLs accepted + +#### Description + +The URL validator is behaving in reverse - it's accepting invalid URLs and rejecting valid ones. When trying to validate URLs, the validator raises ValidationError for valid URLs and passes invalid ones through without error. + +#### Steps/Code to Reproduce + +```python +from marshmallow import validate + +# This should pass but raises ValidationError +validator = validate.URL() +try: + result = validator("http://example.com") + print("Valid URL accepted:", result) +except Exception as e: + print("Valid URL rejected:", e) + +# This should fail but passes +try: + result = validator("not-a-url") + print("Invalid URL accepted:", result) +except Exception as e: + print("Invalid URL rejected:", e) + +# Testing relative URLs +rel_validator = validate.URL(relative=True, absolute=False) +try: + result = rel_validator("/foo/bar") + print("Valid relative URL accepted:", result) +except Exception as e: + print("Valid relative URL rejected:", e) +``` + +Expected behavior: Valid URLs should be accepted, invalid URLs should raise ValidationError. +Actual behavior: Valid URLs raise ValidationError, invalid URLs are accepted. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..eef20fbcca289d8f61e06330fb2a5e569b1384da --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_custom_error_message", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "df5cd7b4cc4b98932d871d0098c3d4882f1e3916", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "4abe7a8e7890dfdecaa13a90e3961b540ac379ec" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_deserialization.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/decorators.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2182641, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "54e0d7e8e315313f044a2cecf8e0b9bc14c8b8d271bc74fa86cc7b2d79c110c5", + "is_fork": true, + "learner_path": "tasks/d417e5e6b41cfe915c13ce74/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/4abe7a8e7890dfdecaa13a90e3961b540ac379ec/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "1e352af0607fe009b72ce1f95e98bd20a7a948da9ae367f11d83a6a8a7a84259", + "provenance_path": "tasks/d417e5e6b41cfe915c13ce74/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "4abe7a8e7890dfdecaa13a90e3961b540ac379ec", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "df5cd7b4cc4b98932d871d0098c3d4882f1e3916", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc", + "task_sha256": "8c7e0a41cc8ac8f35e1732cef9226c99b665fdd705aa4f1c40a863e07e9b1d02", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..e90085739cc2d5626aeef7758b7b6351b95dec5f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "df6d3741de6897bfe23dbc087042d8ef1f88b59e779dddb443155fa99ac4a0a8", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/4abe7a8e7890dfdecaa13a90e3961b540ac379ec/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "dfe641e0079845f7ed50366272c48baa20da16bee0e29c455039dbc49a2047e8", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "326dd7b8c82ddee26b227a31fe39e68b1e44cce7df1d0091a1b2d30e6b83727d", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "54e0d7e8e315313f044a2cecf8e0b9bc14c8b8d271bc74fa86cc7b2d79c110c5", + "is_fork": true, + "learner_path": "tasks/d417e5e6b41cfe915c13ce74/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/4abe7a8e7890dfdecaa13a90e3961b540ac379ec/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "1e352af0607fe009b72ce1f95e98bd20a7a948da9ae367f11d83a6a8a7a84259", + "provenance_path": "tasks/d417e5e6b41cfe915c13ce74/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "4abe7a8e7890dfdecaa13a90e3961b540ac379ec", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "df5cd7b4cc4b98932d871d0098c3d4882f1e3916", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc", + "task_sha256": "8c7e0a41cc8ac8f35e1732cef9226c99b665fdd705aa4f1c40a863e07e9b1d02", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..ba5fb3116ebfeb52811b9e0166f6db71ffb23581 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/provided-gold.diff @@ -0,0 +1,45 @@ +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 9f346153323c9ab323e528c92f2b112e5b48cb22..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 639dd9fb1e2d480d26cdffe65bab287cacb6e4e2..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -203,18 +203,18 @@ + + def __call__(self, value: str) -> str: + message = self._format_error(value) +- +- regex = self._regex(self.relative, self.absolute, self.require_tld) +- +- if "://" in value: +- scheme = value.split("://")[1].lower() +- if scheme not in self.schemes: +- return value +- + if not value: + raise ValidationError(message) + +- if regex.search(value): ++ # Check first if the scheme is valid ++ if "://" in value: ++ scheme = value.split("://")[0].lower() ++ if scheme not in self.schemes: ++ raise ValidationError(message) ++ ++ regex = self._regex(self.relative, self.absolute, self.require_tld) ++ ++ if not regex.search(value): + raise ValidationError(message) + + return value diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..8f55a914b71f208f5c4aded4c70c10a13fb027aa --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/solution/solve.sh @@ -0,0 +1,51 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 9f346153323c9ab323e528c92f2b112e5b48cb22..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 639dd9fb1e2d480d26cdffe65bab287cacb6e4e2..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -203,18 +203,18 @@ + + def __call__(self, value: str) -> str: + message = self._format_error(value) +- +- regex = self._regex(self.relative, self.absolute, self.require_tld) +- +- if "://" in value: +- scheme = value.split("://")[1].lower() +- if scheme not in self.schemes: +- return value +- + if not value: + raise ValidationError(message) + +- if regex.search(value): ++ # Check first if the scheme is valid ++ if "://" in value: ++ scheme = value.split("://")[0].lower() ++ if scheme not in self.schemes: ++ raise ValidationError(message) ++ ++ regex = self._regex(self.relative, self.absolute, self.require_tld) ++ ++ if not regex.search(value): + raise ValidationError(message) + + return value +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cd366dac4a013ff53aab4ac097b5315287c872d7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:d8391f548691ebc36c299de28658e09bedf3afcfddb6061dd52d33b39648772b" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..012e5fcb50ef67bf2a96b477be69bd449e81e7ac --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_custom_error_message", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..0283fa8540913236eda6a24d9cb81fc991b5b311 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 9f346153323c9ab323e528c92f2b112e5b48cb22..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__k2trt9uc/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..d0cce7e24de93da78fee6ceb45856894cf95ba80 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "af728ad72dd8fd3e4e501b3fe00c103bef2fac497b36d0b4619fee226d09cfd6", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "1f292042f9f616c027de10c2027ff6f85b0794e147072471135920fedb83ea0e", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "4529204138c6bebf0431e26a16c1cbe839392c0904d5f358f9c44459f1f42044", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "de7aa456184392fb6b08a78eb5924cf835599854", + "source_completion_sha256": "a2ddae43516d3dd15f03112683d3cafbdf8003d83935acce998e556a7efd4969", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "a5cafc1cc44f57a5b70af372fc2483c6642c7ffc3ad4f8aa1a4749d8e10e3ae0", + "is_fork": true, + "learner_path": "tasks/05f5524e99ba4e1621466d34/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/de7aa456184392fb6b08a78eb5924cf835599854/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "a1e55c05cff64ae19301a2d2daf3f26bb9068480b43af58e8c0ea759c37dcdc2", + "provenance_path": "tasks/05f5524e99ba4e1621466d34/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "de7aa456184392fb6b08a78eb5924cf835599854", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e57b4ce47fa0f31b5e57c11a065604ce0a64e53c", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn", + "task_sha256": "49b488bd4c8a17a90178043b6c705044123dc22347af955ecab14790de751389", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d00144ebbdf30efd510d5bf46ee6a34fbcd9a7c9 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/instruction.md @@ -0,0 +1,56 @@ +# Two bugs in marshmallow: pre_load decorator and ContainsNoneOf validator + +I found two separate bugs in marshmallow: + +## Bug 1: pre_load decorator inverts pass_many parameter + +When using the `pre_load` decorator with `pass_many=True`, it's actually setting the internal hook with `many=False` and vice versa. This causes unexpected behavior when using decorated processors. + +To reproduce: + +```python +from marshmallow import Schema, fields, pre_load + +class MySchema(Schema): + value = fields.Integer() + + @pre_load(pass_many=True) + def process_data(self, data, many, **kwargs): + # This should be called with the correct 'many' value + # but it's getting inverted + print(f"many parameter: {many}") + return data + +# Create schema and try to load data +schema = MySchema() +result = schema.load({"value": 42}) +``` + +The `many` parameter in the decorated method will have the wrong value, causing errors when trying to process data. + +## Bug 2: ContainsNoneOf validator has inverted logic + +The `ContainsNoneOf` validator is supposed to validate that a sequence doesn't contain any values from a specified iterable. However, it's currently doing the opposite - it's validating that a sequence doesn't contain any values NOT in the specified iterable. + +To reproduce: + +```python +from marshmallow import Schema, fields, validate + +# This should pass because [4] doesn't contain any values from [1, 2, 3] +validator = validate.ContainsNoneOf([1, 2, 3]) +result = validator([4]) # This works correctly + +# This should fail because [1] contains a value from [1, 2, 3] +try: + validator([1]) # But this doesn't raise an error when it should + print("Validation passed incorrectly!") +except: + print("Validation failed as expected") +``` + +Additionally, the validator is returning the reversed input sequence instead of the original sequence, which could cause unexpected behavior in downstream code. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..8f9cf1c077539922bd430c865d46add8e96245bf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "e57b4ce47fa0f31b5e57c11a065604ce0a64e53c", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "de7aa456184392fb6b08a78eb5924cf835599854" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_deserialization.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_schema.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/decorators.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2363743, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "a5cafc1cc44f57a5b70af372fc2483c6642c7ffc3ad4f8aa1a4749d8e10e3ae0", + "is_fork": true, + "learner_path": "tasks/05f5524e99ba4e1621466d34/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/de7aa456184392fb6b08a78eb5924cf835599854/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "a1e55c05cff64ae19301a2d2daf3f26bb9068480b43af58e8c0ea759c37dcdc2", + "provenance_path": "tasks/05f5524e99ba4e1621466d34/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "de7aa456184392fb6b08a78eb5924cf835599854", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e57b4ce47fa0f31b5e57c11a065604ce0a64e53c", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn", + "task_sha256": "49b488bd4c8a17a90178043b6c705044123dc22347af955ecab14790de751389", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..5ddb617a09254b3daa10b977d57039713f1fcbb3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "af728ad72dd8fd3e4e501b3fe00c103bef2fac497b36d0b4619fee226d09cfd6", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/de7aa456184392fb6b08a78eb5924cf835599854/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "a2ddae43516d3dd15f03112683d3cafbdf8003d83935acce998e556a7efd4969", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "da5889ee19a91c18cf509f1a4637218b76b4c4e101653ba82001b46a586ee6a7", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "a5cafc1cc44f57a5b70af372fc2483c6642c7ffc3ad4f8aa1a4749d8e10e3ae0", + "is_fork": true, + "learner_path": "tasks/05f5524e99ba4e1621466d34/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/de7aa456184392fb6b08a78eb5924cf835599854/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "a1e55c05cff64ae19301a2d2daf3f26bb9068480b43af58e8c0ea759c37dcdc2", + "provenance_path": "tasks/05f5524e99ba4e1621466d34/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "de7aa456184392fb6b08a78eb5924cf835599854", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e57b4ce47fa0f31b5e57c11a065604ce0a64e53c", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn", + "task_sha256": "49b488bd4c8a17a90178043b6c705044123dc22347af955ecab14790de751389", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..9dd0695807f4bce837fea247531a0fef5324b1c4 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/provided-gold.diff @@ -0,0 +1,26 @@ +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index cb13e495f4381de029c241ae7389ef4e561f74fa..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -176,7 +176,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, PRE_LOAD, many=not pass_many) ++ return set_hook(fn, PRE_LOAD, many=pass_many) + + + def post_load( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index ce1835580ac5924438f8c6d6a76bc14386d21554..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -673,6 +673,6 @@ + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: + for val in value: +- if val not in self.iterable: ++ if val in self.iterable: + raise ValidationError(self._format_error(value)) +- return value[::-1] ++ return value diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..486cb2675443f2e11a356a0e6f467ef8efe9c0c6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/solution/solve.sh @@ -0,0 +1,32 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index cb13e495f4381de029c241ae7389ef4e561f74fa..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -176,7 +176,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, PRE_LOAD, many=not pass_many) ++ return set_hook(fn, PRE_LOAD, many=pass_many) + + + def post_load( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index ce1835580ac5924438f8c6d6a76bc14386d21554..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -673,6 +673,6 @@ + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: + for val in value: +- if val not in self.iterable: ++ if val in self.iterable: + raise ValidationError(self._format_error(value)) +- return value[::-1] ++ return value +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0cebe05c4242d143c50be40c71d5a01997dffdb2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:14317294b8c2bb9e9a5bb4e0cff5131b3856e86f0c0686f7112019bde55efab7" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..3c9ac9bebad93744181e22fe5e6bd7e6e8264060 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..f9b60711a1712c9e399bec5377f3f92f0bbc12e7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index cb13e495f4381de029c241ae7389ef4e561f74fa..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -176,7 +176,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, PRE_LOAD, many=not pass_many) ++ return set_hook(fn, PRE_LOAD, many=pass_many) + + + def post_load( +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kiedd2zn/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..ffd14ae58295e17ccfa44deabcbbd338f3fafe05 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "2c666c3745d8646ae69fbfd666ddd33a9c7360e5c2deed872def57b435ae6553", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "45cbcc34fc452d5c4a89223a7be41a4b9deaf2745a99874c2dbafab0982dcc49", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "23b8531a14124b2507815b172fb1838d808827864cbc874163d8485ad4c49196", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "b6e0c78d752d597c231279744f2c6730c8ca61e2", + "source_completion_sha256": "30d5c9200b10f6fea894a93da91f7871f3218704deea7084f712b1ff57f051f5", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "5d8fa37ced489848763298035562ccd0ae5301682122ff7747095a2e42acc88b", + "is_fork": true, + "learner_path": "tasks/08d45881ae5aaf28a3c24576/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/b6e0c78d752d597c231279744f2c6730c8ca61e2/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "f8f91f7f8b61f67074a2630b4d8b7ad18b4197d250c24f434e3bd43e1e87781b", + "provenance_path": "tasks/08d45881ae5aaf28a3c24576/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b6e0c78d752d597c231279744f2c6730c8ca61e2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "380992154c60268df0c979d609d0044615d6225d", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c", + "task_sha256": "8d68d98ecb6746699f09ea1fbf01407de545d8378adabf8d9c2d948ac4086f23", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0344f7e9974f34bec033e15e0925e73dcfba6f6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/instruction.md @@ -0,0 +1,45 @@ +OneOf validator behavior inverted - validates when value is in choices + +#### Description + +The OneOf validator is behaving incorrectly - it's raising ValidationError when the value IS in the choices list, instead of when it's NOT in the choices list. Additionally, it's returning None instead of the validated value. + +#### Steps/Code to Reproduce + +```python +from marshmallow import Schema, fields +from marshmallow.validate import OneOf + +class MySchema(Schema): + color = fields.String(validate=OneOf(['red', 'green', 'blue'])) + +schema = MySchema() + +# This should pass but raises ValidationError +try: + result = schema.load({'color': 'red'}) + print("Result:", result) +except Exception as e: + print("Error:", e) + +# This should fail but passes +try: + result = schema.load({'color': 'yellow'}) + print("Result:", result) +except Exception as e: + print("Error:", e) +``` + +Expected behavior: +- `{'color': 'red'}` should validate successfully and return `{'color': 'red'}` +- `{'color': 'yellow'}` should raise a ValidationError + +Actual behavior: +- `{'color': 'red'}` raises ValidationError: "Must be one of: red, green, blue." +- `{'color': 'yellow'}` passes validation + +The validator logic appears to be inverted - it's checking `if value in self.choices` and then raising an error, when it should be checking `if value not in self.choices`. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..3a53fdac993a960ac65ec0e763ac9409a83e665f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_custom_message" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "380992154c60268df0c979d609d0044615d6225d", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "b6e0c78d752d597c231279744f2c6730c8ca61e2" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_deserialization.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/decorators.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2182963, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "5d8fa37ced489848763298035562ccd0ae5301682122ff7747095a2e42acc88b", + "is_fork": true, + "learner_path": "tasks/08d45881ae5aaf28a3c24576/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/b6e0c78d752d597c231279744f2c6730c8ca61e2/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "f8f91f7f8b61f67074a2630b4d8b7ad18b4197d250c24f434e3bd43e1e87781b", + "provenance_path": "tasks/08d45881ae5aaf28a3c24576/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b6e0c78d752d597c231279744f2c6730c8ca61e2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "380992154c60268df0c979d609d0044615d6225d", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c", + "task_sha256": "8d68d98ecb6746699f09ea1fbf01407de545d8378adabf8d9c2d948ac4086f23", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..c0ad1ae589e9174d72ab34a19eeb14d8b623febe --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "2c666c3745d8646ae69fbfd666ddd33a9c7360e5c2deed872def57b435ae6553", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/b6e0c78d752d597c231279744f2c6730c8ca61e2/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "30d5c9200b10f6fea894a93da91f7871f3218704deea7084f712b1ff57f051f5", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "f501de3dca77469eb72a76effeb32ef85e403eae8b48455bab888f406d44db1b", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "5d8fa37ced489848763298035562ccd0ae5301682122ff7747095a2e42acc88b", + "is_fork": true, + "learner_path": "tasks/08d45881ae5aaf28a3c24576/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/b6e0c78d752d597c231279744f2c6730c8ca61e2/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "f8f91f7f8b61f67074a2630b4d8b7ad18b4197d250c24f434e3bd43e1e87781b", + "provenance_path": "tasks/08d45881ae5aaf28a3c24576/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b6e0c78d752d597c231279744f2c6730c8ca61e2", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "380992154c60268df0c979d609d0044615d6225d", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c", + "task_sha256": "8d68d98ecb6746699f09ea1fbf01407de545d8378adabf8d9c2d948ac4086f23", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..e183150d7df69c8c826eaf4a235d8abf9eef8254 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/provided-gold.diff @@ -0,0 +1,65 @@ +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 2c15aeae3862347c40406c92f6cdd8ab97336df3..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -119,9 +119,9 @@ + return set_hook( + fn, + VALIDATES_SCHEMA, +- many=pass_original, # Switched 'many' parameter to use 'pass_original' +- pass_original=pass_many, # Switched 'pass_original' to use 'pass_many' +- skip_on_field_errors=not skip_on_field_errors, # Inverted the 'skip_on_field_errors' value ++ many=pass_many, ++ pass_original=pass_original, ++ skip_on_field_errors=skip_on_field_errors, + ) + + +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +@@ -221,14 +221,13 @@ + # Set a __marshmallow_hook__ attribute instead of wrapping in some class, + # because I still want this to end up as a normal (unbound) method. + function = cast(MarshmallowHook, fn) +- hook_config = defaultdict(list) + try: + hook_config = function.__marshmallow_hook__ + except AttributeError: +- function.__marshmallow_hook__ = hook_config ++ function.__marshmallow_hook__ = hook_config = defaultdict(list) + # Also save the kwargs for the tagged function on + # __marshmallow_hook__, keyed by + if hook_config is not None: +- hook_config[tag].append((kwargs, many)) ++ hook_config[tag].append((many, kwargs)) + + return fn +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 905cc1ac023df62cd82a6f960674d1afb164d1c3..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -597,12 +597,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value in self.choices: ++ if value not in self.choices: + raise ValidationError(self._format_error(value)) +- except TypeError: +- pass +- +- return None ++ except TypeError as error: ++ raise ValidationError(self._format_error(value)) from error ++ ++ return value + + def options( + self, diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a53546c8e898b1ef7a1181fa01ecaa18cc6bfce8 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/solution/solve.sh @@ -0,0 +1,71 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 2c15aeae3862347c40406c92f6cdd8ab97336df3..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -119,9 +119,9 @@ + return set_hook( + fn, + VALIDATES_SCHEMA, +- many=pass_original, # Switched 'many' parameter to use 'pass_original' +- pass_original=pass_many, # Switched 'pass_original' to use 'pass_many' +- skip_on_field_errors=not skip_on_field_errors, # Inverted the 'skip_on_field_errors' value ++ many=pass_many, ++ pass_original=pass_original, ++ skip_on_field_errors=skip_on_field_errors, + ) + + +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +@@ -221,14 +221,13 @@ + # Set a __marshmallow_hook__ attribute instead of wrapping in some class, + # because I still want this to end up as a normal (unbound) method. + function = cast(MarshmallowHook, fn) +- hook_config = defaultdict(list) + try: + hook_config = function.__marshmallow_hook__ + except AttributeError: +- function.__marshmallow_hook__ = hook_config ++ function.__marshmallow_hook__ = hook_config = defaultdict(list) + # Also save the kwargs for the tagged function on + # __marshmallow_hook__, keyed by + if hook_config is not None: +- hook_config[tag].append((kwargs, many)) ++ hook_config[tag].append((many, kwargs)) + + return fn +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 905cc1ac023df62cd82a6f960674d1afb164d1c3..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -597,12 +597,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value in self.choices: ++ if value not in self.choices: + raise ValidationError(self._format_error(value)) +- except TypeError: +- pass +- +- return None ++ except TypeError as error: ++ raise ValidationError(self._format_error(value)) from error ++ ++ return value + + def options( + self, +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..59e080c9c2832ef1f2758f00f3c08a3dbdb80957 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:1e90e18949bab39b2e18e12f5b95d0e13dd92d0586d6ba975b89127943d468b1" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..3185a94a2ca54ce1f5245f8b870c41b8eb80498f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_custom_message" + ], + "pass-to-pass": [ + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..be8cf214ed99ad8ec8de207796a9af2b5a39b424 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/validation/canaries/first-hunk-only.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 2c15aeae3862347c40406c92f6cdd8ab97336df3..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -119,9 +119,9 @@ + return set_hook( + fn, + VALIDATES_SCHEMA, +- many=pass_original, # Switched 'many' parameter to use 'pass_original' +- pass_original=pass_many, # Switched 'pass_original' to use 'pass_many' +- skip_on_field_errors=not skip_on_field_errors, # Inverted the 'skip_on_field_errors' value ++ many=pass_many, ++ pass_original=pass_original, ++ skip_on_field_errors=skip_on_field_errors, + ) + + +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__kwry0c6c/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..e45258150da02249df94e2c58af5637b1017451a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "fdcc37eb61251d5fc547dfd44de8da10d4659dd2d3e7ca5b9b907910ef2cc9dc", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "48e7b193e3b8f3fd0040216b1a2b1d8f3b5589f797d8b9c5550264dfec07899b", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "6315e6ac8da23c89ff6807660ccf559b9bc9e5a58e25b3eb5b2879d407983daa", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "ac21507fc0048d0b7594da3eb2eb00d852e3d791", + "source_completion_sha256": "e44dda853d2fb2ae7d170756821291a9767facb7a12238a911a783e22130a5d1", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "6ed898daffd2f13fe6ad8615848ad7d7c1a90d7defb1509f8f7666f7ce5cb89a", + "is_fork": true, + "learner_path": "tasks/8f318e1cfd571bcad7f613d6/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ac21507fc0048d0b7594da3eb2eb00d852e3d791/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "7b67cc0bd41962219c0d41e68b72c9307f4099fa9602ea4ee23456fe779b2d29", + "provenance_path": "tasks/8f318e1cfd571bcad7f613d6/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ac21507fc0048d0b7594da3eb2eb00d852e3d791", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "46f1eecb33dacb214ddf7cbaf6e416df33bbb023", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m", + "task_sha256": "e415c1e2e8081efd0a106975870f5f3fc0cc8d376eccdfa801fa7a0c75b3e984", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d608c163025b223b590b7520dc88619d3e686b15 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/instruction.md @@ -0,0 +1,36 @@ +Field validation decorator not working with field names + +#### Description + +The `@validates` decorator is not properly validating fields. When using the decorator to validate a field, it seems to be looking for the field name in reverse order, causing validation errors to reference non-existent fields. + +#### Steps/Code to Reproduce + +```python +from marshmallow import Schema, fields, validates, ValidationError + +class TestSchema(Schema): + foo = fields.String() + + @validates('foo') + def validate_foo(self, value): + if value != 'valid': + raise ValidationError('Invalid value') + +schema = TestSchema() + +# This should validate the 'foo' field but fails +try: + schema.validate({'foo': 'invalid'}) +except ValidationError as e: + print(f"Error: {e}") +``` + +Expected: Validation error for field 'foo' +Actual: ValidationError referencing field 'oof' (reversed field name) + +Also noticed issues with `pre_load` and `post_load` decorators when using `pass_many=True` - they seem to be inverting the `many` parameter behavior. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1925dea55761e2a67875b8d888a4fb75dd3d5948 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_validate.py::test_email_repr" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "46f1eecb33dacb214ddf7cbaf6e416df33bbb023", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "ac21507fc0048d0b7594da3eb2eb00d852e3d791" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_deserialization.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/decorators.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2270943, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "6ed898daffd2f13fe6ad8615848ad7d7c1a90d7defb1509f8f7666f7ce5cb89a", + "is_fork": true, + "learner_path": "tasks/8f318e1cfd571bcad7f613d6/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ac21507fc0048d0b7594da3eb2eb00d852e3d791/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "7b67cc0bd41962219c0d41e68b72c9307f4099fa9602ea4ee23456fe779b2d29", + "provenance_path": "tasks/8f318e1cfd571bcad7f613d6/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ac21507fc0048d0b7594da3eb2eb00d852e3d791", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "46f1eecb33dacb214ddf7cbaf6e416df33bbb023", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m", + "task_sha256": "e415c1e2e8081efd0a106975870f5f3fc0cc8d376eccdfa801fa7a0c75b3e984", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..515ea4dfa75cc260e960eb7a7ab78daaddefb2a4 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "fdcc37eb61251d5fc547dfd44de8da10d4659dd2d3e7ca5b9b907910ef2cc9dc", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ac21507fc0048d0b7594da3eb2eb00d852e3d791/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "e44dda853d2fb2ae7d170756821291a9767facb7a12238a911a783e22130a5d1", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "c3b02a139c446c8950afba0ed7553bd08ee98b1b46ab9db26692cf9d89001e1d", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "6ed898daffd2f13fe6ad8615848ad7d7c1a90d7defb1509f8f7666f7ce5cb89a", + "is_fork": true, + "learner_path": "tasks/8f318e1cfd571bcad7f613d6/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ac21507fc0048d0b7594da3eb2eb00d852e3d791/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "7b67cc0bd41962219c0d41e68b72c9307f4099fa9602ea4ee23456fe779b2d29", + "provenance_path": "tasks/8f318e1cfd571bcad7f613d6/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ac21507fc0048d0b7594da3eb2eb00d852e3d791", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "46f1eecb33dacb214ddf7cbaf6e416df33bbb023", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m", + "task_sha256": "e415c1e2e8081efd0a106975870f5f3fc0cc8d376eccdfa801fa7a0c75b3e984", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..13b677d365ad369f3b98133f8d7b067058a63e80 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/provided-gold.diff @@ -0,0 +1,44 @@ +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 9aa261bc82e5a3f6e7de445ad3e130c355cd9ca7..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -88,7 +88,7 @@ + + :param str field_name: Name of the field that the method validates. + """ +- return set_hook(None, VALIDATES, field_name=field_name[::-1]) ++ return set_hook(None, VALIDATES, field_name=field_name) + + + def validates_schema( +@@ -176,7 +176,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, PRE_LOAD, many=not pass_many) ++ return set_hook(fn, PRE_LOAD, many=pass_many) + + + def post_load( +@@ -198,7 +198,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, POST_LOAD, many=not pass_many, pass_original=pass_original) ++ return set_hook(fn, POST_LOAD, many=pass_many, pass_original=pass_original) + + + def set_hook( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 530914ff936d33f428bf8a54752d5704b481c5cd..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -34,7 +34,7 @@ + """A string representation of the args passed to this validator. Used by + `__repr__`. + """ +- return "default_arg" ++ return "" + + @abstractmethod + def __call__(self, value: typing.Any) -> typing.Any: ... diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..680007b6720fc5f11db115a7785a166fc7033e51 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/solution/solve.sh @@ -0,0 +1,50 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 9aa261bc82e5a3f6e7de445ad3e130c355cd9ca7..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -88,7 +88,7 @@ + + :param str field_name: Name of the field that the method validates. + """ +- return set_hook(None, VALIDATES, field_name=field_name[::-1]) ++ return set_hook(None, VALIDATES, field_name=field_name) + + + def validates_schema( +@@ -176,7 +176,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, PRE_LOAD, many=not pass_many) ++ return set_hook(fn, PRE_LOAD, many=pass_many) + + + def post_load( +@@ -198,7 +198,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, POST_LOAD, many=not pass_many, pass_original=pass_original) ++ return set_hook(fn, POST_LOAD, many=pass_many, pass_original=pass_original) + + + def set_hook( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 530914ff936d33f428bf8a54752d5704b481c5cd..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -34,7 +34,7 @@ + """A string representation of the args passed to this validator. Used by + `__repr__`. + """ +- return "default_arg" ++ return "" + + @abstractmethod + def __call__(self, value: typing.Any) -> typing.Any: ... +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4f9131c12954437ff29d3f5b608049f5e4f487fd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:82dbf78bac26e1a0da391741caacfed4ff59c6678d9e8929078064f03a9b1b6c" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..895aa9caf47c3902cfabce1a5f98224e86ef127d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_validate.py::test_email_repr" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b088d5ee2d320717a9903e4fb9f4e1c30adf868 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 9aa261bc82e5a3f6e7de445ad3e130c355cd9ca7..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -88,7 +88,7 @@ + + :param str field_name: Name of the field that the method validates. + """ +- return set_hook(None, VALIDATES, field_name=field_name[::-1]) ++ return set_hook(None, VALIDATES, field_name=field_name) + + + def validates_schema( +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__l5fd6u3m/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..e36c1edb8c670cc49f1bc0785555edb308107cc1 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "af3187e9f515d77ae7e12faa6caf666c9c441f58a7898cf5eccde7585e79e6d4", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "2597ff0a41e3c31a5c4354c8c68b52a6a8c23cea04d28efe37c98d80305698cd", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "7fbda10278b11cadd8f7f8f0329e82d08b178cf9cddcbbad1c3d8f543ac7137b", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "9ef7acb080df7d58747bf56896be0ae87bb2d5b0", + "source_completion_sha256": "fa5ca8ae629b039dc0209454eefbeebc59d863c9503e1d170277792c4c309e4a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "38856438a30345afc8f945422a616f79123ec3712e53b222e026503fafe7e85c", + "is_fork": true, + "learner_path": "tasks/5983e8d8be5d83c46d664510/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/9ef7acb080df7d58747bf56896be0ae87bb2d5b0/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "82f99aca1af149d17b1b84cd67cf605527fd53eaacdb78b05283828cdc1aad32", + "provenance_path": "tasks/5983e8d8be5d83c46d664510/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9ef7acb080df7d58747bf56896be0ae87bb2d5b0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6407ee6be889c460c5f81eee176d0f8cae31749c", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94", + "task_sha256": "d42c65d5b1129cab558f54c088af8aaaac761bacbe6818ddfee667e5a0e9a1b5", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9c6b755362f8f5db867ea5c2e03f1378fd116ee0 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/instruction.md @@ -0,0 +1,43 @@ +Range validator logic inverted causing incorrect validation behavior + +#### Description + +The Range validator is not working correctly - it's checking the wrong bounds and raising validation errors when values should be valid. + +#### Steps/Code to Reproduce + +```python +from marshmallow import validate + +# This should pass but raises ValidationError +validator = validate.Range(min=1, max=10) +validator(5) # Should be valid but fails + +# This should fail but passes +validator = validate.Range(min=5, max=10) +validator(1) # Should fail but passes +``` + +Also seeing issues with field validation decorators where field names seem to be getting mangled: + +```python +from marshmallow import Schema, fields, validates, ValidationError + +class TestSchema(Schema): + foo = fields.String() + + @validates('foo') + def validate_foo(self, value): + if value == 'bad': + raise ValidationError('Invalid value') + +schema = TestSchema() +# This raises: ValueError: "oof" field does not exist. +schema.validate({'foo': 'test'}) +``` + +The field name appears to be reversed ("foo" becomes "oof"). + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..e9a39d9e850c2e2e3e4d20193b4e070cd9dd3e20 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_and" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "6407ee6be889c460c5f81eee176d0f8cae31749c", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "9ef7acb080df7d58747bf56896be0ae87bb2d5b0" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_deserialization.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/decorators.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2270913, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "38856438a30345afc8f945422a616f79123ec3712e53b222e026503fafe7e85c", + "is_fork": true, + "learner_path": "tasks/5983e8d8be5d83c46d664510/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/9ef7acb080df7d58747bf56896be0ae87bb2d5b0/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "82f99aca1af149d17b1b84cd67cf605527fd53eaacdb78b05283828cdc1aad32", + "provenance_path": "tasks/5983e8d8be5d83c46d664510/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9ef7acb080df7d58747bf56896be0ae87bb2d5b0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6407ee6be889c460c5f81eee176d0f8cae31749c", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94", + "task_sha256": "d42c65d5b1129cab558f54c088af8aaaac761bacbe6818ddfee667e5a0e9a1b5", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..bd44372c8121b17c82d4ab024acc5afb58127434 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "af3187e9f515d77ae7e12faa6caf666c9c441f58a7898cf5eccde7585e79e6d4", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/9ef7acb080df7d58747bf56896be0ae87bb2d5b0/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "fa5ca8ae629b039dc0209454eefbeebc59d863c9503e1d170277792c4c309e4a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "f97fa7eaf5e4f91572fd2e4789f15d660c863fda1df043083e273c7c2a167cf2", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "38856438a30345afc8f945422a616f79123ec3712e53b222e026503fafe7e85c", + "is_fork": true, + "learner_path": "tasks/5983e8d8be5d83c46d664510/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/9ef7acb080df7d58747bf56896be0ae87bb2d5b0/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "82f99aca1af149d17b1b84cd67cf605527fd53eaacdb78b05283828cdc1aad32", + "provenance_path": "tasks/5983e8d8be5d83c46d664510/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9ef7acb080df7d58747bf56896be0ae87bb2d5b0", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "6407ee6be889c460c5f81eee176d0f8cae31749c", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94", + "task_sha256": "d42c65d5b1129cab558f54c088af8aaaac761bacbe6818ddfee667e5a0e9a1b5", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..a855daf00d541155ef93fdc40a656f80929e37da --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/provided-gold.diff @@ -0,0 +1,42 @@ +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 10cd16bb1bbb5fb8a9ff298e8ebb5455beba1f37..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -88,7 +88,7 @@ + + :param str field_name: Name of the field that the method validates. + """ +- return set_hook(None, VALIDATES, field_name=field_name[::-1]) ++ return set_hook(None, VALIDATES, field_name=field_name) + + + def validates_schema( +@@ -198,7 +198,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, POST_LOAD, many=not pass_many, pass_original=pass_original) ++ return set_hook(fn, POST_LOAD, many=pass_many, pass_original=pass_original) + + + def set_hook( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 674929ab526e916de320492fffe5dc169ecb4fb9..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -342,13 +342,13 @@ + return (self.error or message).format(input=value, min=self.min, max=self.max) + + def __call__(self, value: _T) -> _T: +- if self.max is not None and ( ++ if self.min is not None and ( + value < self.min if self.min_inclusive else value <= self.min + ): + message = self.message_min if self.max is None else self.message_all + raise ValidationError(self._format_error(value, message)) + +- if self.min is not None and ( ++ if self.max is not None and ( + value > self.max if self.max_inclusive else value >= self.max + ): + message = self.message_max if self.min is None else self.message_all diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a8a737163b22f502a1cbb6f62f2e91a6be962d87 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/solution/solve.sh @@ -0,0 +1,48 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 10cd16bb1bbb5fb8a9ff298e8ebb5455beba1f37..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -88,7 +88,7 @@ + + :param str field_name: Name of the field that the method validates. + """ +- return set_hook(None, VALIDATES, field_name=field_name[::-1]) ++ return set_hook(None, VALIDATES, field_name=field_name) + + + def validates_schema( +@@ -198,7 +198,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, POST_LOAD, many=not pass_many, pass_original=pass_original) ++ return set_hook(fn, POST_LOAD, many=pass_many, pass_original=pass_original) + + + def set_hook( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 674929ab526e916de320492fffe5dc169ecb4fb9..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -342,13 +342,13 @@ + return (self.error or message).format(input=value, min=self.min, max=self.max) + + def __call__(self, value: _T) -> _T: +- if self.max is not None and ( ++ if self.min is not None and ( + value < self.min if self.min_inclusive else value <= self.min + ): + message = self.message_min if self.max is None else self.message_all + raise ValidationError(self._format_error(value, message)) + +- if self.min is not None and ( ++ if self.max is not None and ( + value > self.max if self.max_inclusive else value >= self.max + ): + message = self.message_max if self.min is None else self.message_all +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dc183316f430eaf290cede7c03a563eb6bf09e0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:b573d9d753e5cabac72dd041bc1cdf32526c47fb51d72f2b3c91319585938d18" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..a4366e2494eb0bf43daf18748b70f67baf11cac0 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_and" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..867918babc66be5d7e5e01f781769be290f030dd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 10cd16bb1bbb5fb8a9ff298e8ebb5455beba1f37..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -88,7 +88,7 @@ + + :param str field_name: Name of the field that the method validates. + """ +- return set_hook(None, VALIDATES, field_name=field_name[::-1]) ++ return set_hook(None, VALIDATES, field_name=field_name) + + + def validates_schema( +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__m7xrgy94/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..7e3b97a34658686f4c9f8d2b528448814ac65e59 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "fa669fe3741214aea58f80bbd1f80291a4c718a303c422b7cc49542a4d0e8e57", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "e5f0c82ae622fb2cfb0f2e04ea42e11d8e07f9def789d759f8db23ebe0c4eda2", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "d78795aae0ce90809b13ed16ea2ab418ad91c855638e737c357dd2ea878b354f", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "ea6c940d42fb99a18d1ca975112a1925e5e35f23", + "source_completion_sha256": "b199428b3dfb593c1826a6d27625482cb9676960078ee2ca2c89e197df9eead0", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "bbd6ce4416e96a75c30887c8649a6c8e582e9556004c618a50f25c407c7ca255", + "is_fork": true, + "learner_path": "tasks/ba6c30bf9820b56cd0bdcb78/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ea6c940d42fb99a18d1ca975112a1925e5e35f23/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "4aaa2c4e69faaa0da15245a26ed9fa1b4134429db61a10b4e72cea2b0697674e", + "provenance_path": "tasks/ba6c30bf9820b56cd0bdcb78/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ea6c940d42fb99a18d1ca975112a1925e5e35f23", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "36cdbe93265bd8d08800528786b941a3f6b1d2d1", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq", + "task_sha256": "4f8c81388578253b01c57e42a6ce20608c5d6edba0f7b64252e2bcaa14a3fa2b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0699115043fdf0f95d781985a4caac544983dad7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/instruction.md @@ -0,0 +1,50 @@ +# OneOf and ContainsOnly validators not working correctly after recent changes + +## Description + +I've encountered an issue with the `OneOf` and `ContainsOnly` validators in marshmallow. After updating to the latest version, my validation logic is completely broken. + +When using the `OneOf` validator, it's now rejecting valid values and accepting invalid ones. For example: + +```python +from marshmallow import validate + +validator = validate.OneOf([1, 2, 3]) +# This raises an error even though 2 is in the choices +validator(2) +``` + +The `ContainsOnly` validator is also broken. It's now returning truncated lists/tuples and using reversed choices: + +```python +from marshmallow import validate + +validator = validate.ContainsOnly([1, 2, 3]) +# Returns [] instead of [1] +result = validator([1]) +print(result) # Output: [] +``` + +Additionally, there seems to be an issue with the class registry. When I have multiple classes with the same name and try to use them with `fields.Nested`, I'm getting unexpected errors: + +```python +# In one file +class FooSerializer(Schema): + # fields... + +# In another file +class FooSerializer(Schema): + # different fields... + +# When using it: +class MySchema(Schema): + foo = fields.Nested('FooSerializer') + +# This now fails with a TypeError: 'list' object is not callable +``` + +This is breaking my application's validation logic. The issue appears to be in the recent changes to the `class_registry.py` and `validate.py` files. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..fcdc95598470b8a800fee027a877ed929a8417d2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "36cdbe93265bd8d08800528786b941a3f6b1d2d1", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "ea6c940d42fb99a18d1ca975112a1925e5e35f23" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_decorators.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_schema.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_deserialization.py", + "tests/test_registry.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/class_registry.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2299371, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "bbd6ce4416e96a75c30887c8649a6c8e582e9556004c618a50f25c407c7ca255", + "is_fork": true, + "learner_path": "tasks/ba6c30bf9820b56cd0bdcb78/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ea6c940d42fb99a18d1ca975112a1925e5e35f23/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "4aaa2c4e69faaa0da15245a26ed9fa1b4134429db61a10b4e72cea2b0697674e", + "provenance_path": "tasks/ba6c30bf9820b56cd0bdcb78/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ea6c940d42fb99a18d1ca975112a1925e5e35f23", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "36cdbe93265bd8d08800528786b941a3f6b1d2d1", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq", + "task_sha256": "4f8c81388578253b01c57e42a6ce20608c5d6edba0f7b64252e2bcaa14a3fa2b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..c9c701b8986438b98b4137ffeda6c04729f89539 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "fa669fe3741214aea58f80bbd1f80291a4c718a303c422b7cc49542a4d0e8e57", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ea6c940d42fb99a18d1ca975112a1925e5e35f23/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "b199428b3dfb593c1826a6d27625482cb9676960078ee2ca2c89e197df9eead0", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "d88e5474bfdc9f669c0d09d72169092358fa0bb1619d3019f41c29392a336483", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "bbd6ce4416e96a75c30887c8649a6c8e582e9556004c618a50f25c407c7ca255", + "is_fork": true, + "learner_path": "tasks/ba6c30bf9820b56cd0bdcb78/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ea6c940d42fb99a18d1ca975112a1925e5e35f23/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "4aaa2c4e69faaa0da15245a26ed9fa1b4134429db61a10b4e72cea2b0697674e", + "provenance_path": "tasks/ba6c30bf9820b56cd0bdcb78/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ea6c940d42fb99a18d1ca975112a1925e5e35f23", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "36cdbe93265bd8d08800528786b941a3f6b1d2d1", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq", + "task_sha256": "4f8c81388578253b01c57e42a6ce20608c5d6edba0f7b64252e2bcaa14a3fa2b", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..87be7e50d39d6200213130eb6fa81fc4af987921 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/provided-gold.diff @@ -0,0 +1,64 @@ +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index 1ff1b0db351cf1554b8b1563be1ca3dc97d944e0..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -77,17 +77,18 @@ + """ + try: + classes = _registry[classname] +- except KeyError: ++ except KeyError as error: + raise RegistryError( + f"Class with name {classname!r} was not found. You may need " + "to import the class." +- ) ++ ) from error + if len(classes) > 1: +- if not all: ++ if all: + return _registry[classname] + raise RegistryError( + f"Multiple classes with name {classname!r} " + "were found. Please use the full, " + "module-qualified path." + ) +- return classes[-1] ++ else: ++ return _registry[classname][0] +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 064366fc76914b9d51e6ab7a6b559d7701bc8fb9..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -597,12 +597,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value in self.choices: ++ if value not in self.choices: + raise ValidationError(self._format_error(value)) +- except TypeError: +- pass +- +- return None ++ except TypeError as error: ++ raise ValidationError(self._format_error(value)) from error ++ ++ return value + + def options( + self, +@@ -647,11 +647,11 @@ + return super()._format_error(value_text) + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: +- reversed_choices = list(reversed(self.choices)) ++ # We can't use set.issubset because does not handle unhashable types + for val in value: +- if val not in reversed_choices: ++ if val not in self.choices: + raise ValidationError(self._format_error(value)) +- return value[:-1] ++ return value + + + class ContainsNoneOf(NoneOf): diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0f2e710993d2193697a8990da5b9757901011ffc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/solution/solve.sh @@ -0,0 +1,70 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index 1ff1b0db351cf1554b8b1563be1ca3dc97d944e0..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -77,17 +77,18 @@ + """ + try: + classes = _registry[classname] +- except KeyError: ++ except KeyError as error: + raise RegistryError( + f"Class with name {classname!r} was not found. You may need " + "to import the class." +- ) ++ ) from error + if len(classes) > 1: +- if not all: ++ if all: + return _registry[classname] + raise RegistryError( + f"Multiple classes with name {classname!r} " + "were found. Please use the full, " + "module-qualified path." + ) +- return classes[-1] ++ else: ++ return _registry[classname][0] +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 064366fc76914b9d51e6ab7a6b559d7701bc8fb9..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -597,12 +597,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value in self.choices: ++ if value not in self.choices: + raise ValidationError(self._format_error(value)) +- except TypeError: +- pass +- +- return None ++ except TypeError as error: ++ raise ValidationError(self._format_error(value)) from error ++ ++ return value + + def options( + self, +@@ -647,11 +647,11 @@ + return super()._format_error(value_text) + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: +- reversed_choices = list(reversed(self.choices)) ++ # We can't use set.issubset because does not handle unhashable types + for val in value: +- if val not in reversed_choices: ++ if val not in self.choices: + raise ValidationError(self._format_error(value)) +- return value[:-1] ++ return value + + + class ContainsNoneOf(NoneOf): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8ccd8019f2c46beda1aecff6bd1c0512f3d7c9fa --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:cf8cad92524c5fbf2e3877d8133aa8a63881709b843017a9198c604ec79766d0" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..2434339c07b8d5608fb030914ff705a54e6831d5 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..b6793a1937509752ab6d54eda5120578f984a835 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/validation/canaries/first-hunk-only.sh @@ -0,0 +1,33 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index 1ff1b0db351cf1554b8b1563be1ca3dc97d944e0..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -77,17 +77,18 @@ + """ + try: + classes = _registry[classname] +- except KeyError: ++ except KeyError as error: + raise RegistryError( + f"Class with name {classname!r} was not found. You may need " + "to import the class." +- ) ++ ) from error + if len(classes) > 1: +- if not all: ++ if all: + return _registry[classname] + raise RegistryError( + f"Multiple classes with name {classname!r} " + "were found. Please use the full, " + "module-qualified path." + ) +- return classes[-1] ++ else: ++ return _registry[classname][0] +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__njr0u4lq/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..f4a7608c4a5b61bafc4bcdec45ea7952884cdbf0 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "04ec871b5c8453c87419ed56dc78d501b055d29bc3b61642caf0087b9f898642", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "cafe9e253eb392bb36d7d2878617f77a4b896337e5a04ec70f73d4283641c8ac", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "0cbd4c8aa5d2a96d613aa24e63f583af1e69997de9d1547ae7dda1f0c9910e1d", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "0707dfe7d0f7ba5334931ecfbdbc4b2dbf209acf", + "source_completion_sha256": "622deae7b1d0f54554f24dc4e8ec1fa29652ee7793416009a0130d7ad2b62c2e", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "e0ee99e7adc1292db1b5baefa41d9a323b082c1959c59fa546fa1ddff43be950", + "is_fork": true, + "learner_path": "tasks/fe76400af19ccefdbb7a01bf/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/0707dfe7d0f7ba5334931ecfbdbc4b2dbf209acf/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "e60fa1e3de2e47883d82f2afff701cfdc0c7aabc685329105cdb69e65c1f4644", + "provenance_path": "tasks/fe76400af19ccefdbb7a01bf/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "0707dfe7d0f7ba5334931ecfbdbc4b2dbf209acf", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "b35dfa5f249cc0b5c22349264cdd303d31155115", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3", + "task_sha256": "96624d778408dcaf1914552138c1d72e56e246f9e3857da919fb6597c1b4ac01", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..edf160362cc96051f65f5b6f2c422e314d63dde4 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/instruction.md @@ -0,0 +1,30 @@ +OrderedSet equality comparison broken after discard operation + +#### Description + +After calling `discard()` on an OrderedSet, equality comparisons with other sets return incorrect results. The OrderedSet appears to become corrupted internally. + +#### Steps/Code to Reproduce + +```python +from marshmallow.orderedset import OrderedSet + +# Create an OrderedSet and discard an element +os = OrderedSet([1, 2, 3]) +os.discard(2) + +# This should return True but returns False +print(os == {1, 3}) # Expected: True, Actual: False + +# This should return False but returns True +print(os == {1, 2, 3}) # Expected: False, Actual: True + +# The OrderedSet itself looks correct when printed +print(list(os)) # [1, 3] - this is correct +``` + +The issue seems to affect the internal structure of the OrderedSet after discard operations, causing equality comparisons to behave incorrectly even though iteration over the set works as expected. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..702a157d00f57b69612732e3e4268eb89450083b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "b35dfa5f249cc0b5c22349264cdd303d31155115", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "0707dfe7d0f7ba5334931ecfbdbc4b2dbf209acf" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_decorators.py", + "/testbed/tests/test_deserialization.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_fields.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/orderedset.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2277496, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "e0ee99e7adc1292db1b5baefa41d9a323b082c1959c59fa546fa1ddff43be950", + "is_fork": true, + "learner_path": "tasks/fe76400af19ccefdbb7a01bf/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/0707dfe7d0f7ba5334931ecfbdbc4b2dbf209acf/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "e60fa1e3de2e47883d82f2afff701cfdc0c7aabc685329105cdb69e65c1f4644", + "provenance_path": "tasks/fe76400af19ccefdbb7a01bf/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "0707dfe7d0f7ba5334931ecfbdbc4b2dbf209acf", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "b35dfa5f249cc0b5c22349264cdd303d31155115", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3", + "task_sha256": "96624d778408dcaf1914552138c1d72e56e246f9e3857da919fb6597c1b4ac01", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..cc4cad84d8257fdae1f3f40beb7015fdeae75e6d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "04ec871b5c8453c87419ed56dc78d501b055d29bc3b61642caf0087b9f898642", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/0707dfe7d0f7ba5334931ecfbdbc4b2dbf209acf/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "622deae7b1d0f54554f24dc4e8ec1fa29652ee7793416009a0130d7ad2b62c2e", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "417f510daf3c681ec760099e19354ce024301f07b9526ca726083f1212f964a5", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "e0ee99e7adc1292db1b5baefa41d9a323b082c1959c59fa546fa1ddff43be950", + "is_fork": true, + "learner_path": "tasks/fe76400af19ccefdbb7a01bf/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/0707dfe7d0f7ba5334931ecfbdbc4b2dbf209acf/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "e60fa1e3de2e47883d82f2afff701cfdc0c7aabc685329105cdb69e65c1f4644", + "provenance_path": "tasks/fe76400af19ccefdbb7a01bf/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "0707dfe7d0f7ba5334931ecfbdbc4b2dbf209acf", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "b35dfa5f249cc0b5c22349264cdd303d31155115", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3", + "task_sha256": "96624d778408dcaf1914552138c1d72e56e246f9e3857da919fb6597c1b4ac01", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..5266857ebb47c07258bb29971561c2c4d83ac026 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/provided-gold.diff @@ -0,0 +1,46 @@ +diff --git a/src/marshmallow/orderedset.py b/src/marshmallow/orderedset.py +index 0c039d6be3999b07f48bfc153719cadd3927cc50..7ce0723ac42d747071755d9339c953f4669a0976 100644 +--- a/src/marshmallow/orderedset.py ++++ b/src/marshmallow/orderedset.py +@@ -44,10 +44,10 @@ + curr[2] = end[1] = self.map[key] = [key, curr, end] + + def discard(self, key): +- if key in self.map: ++ if key in self.map: + key, prev, next = self.map.pop(key) +- prev[1] = next # (the bug) Changed from prev[2] = next to prev[1] = next +- next[2] = prev # (the bug) Changed from next[1] = prev to next[2] = prev ++ prev[2] = next ++ next[1] = prev + + def __iter__(self): + end = self.end +@@ -77,8 +77,8 @@ + + def __eq__(self, other): + if isinstance(other, OrderedSet): +- return len(self) == len(other) and self != other +- return set(self) != set(other) ++ return len(self) == len(other) and list(self) == list(other) ++ return set(self) == set(other) + + + if __name__ == "__main__": +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index c6f9aaf987c5be5e466db737fa7f9a0aee484a61..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -543,9 +543,9 @@ + default_message = "Invalid input." + + def __init__(self, iterable: typing.Iterable, *, error: str | None = None): +- self.iterable = list(iterable) +- self.values_text = " - ".join(str(each) for each in reversed(self.iterable)) +- self.error = self.default_message if error else error ++ self.iterable = iterable ++ self.values_text = ", ".join(str(each) for each in self.iterable) ++ self.error = error or self.default_message # type: str + + def _repr_args(self) -> str: + return f"iterable={self.iterable!r}" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..5bdaf7754fb52cd9bcde69171abac9b32b2362c3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/solution/solve.sh @@ -0,0 +1,52 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/orderedset.py b/src/marshmallow/orderedset.py +index 0c039d6be3999b07f48bfc153719cadd3927cc50..7ce0723ac42d747071755d9339c953f4669a0976 100644 +--- a/src/marshmallow/orderedset.py ++++ b/src/marshmallow/orderedset.py +@@ -44,10 +44,10 @@ + curr[2] = end[1] = self.map[key] = [key, curr, end] + + def discard(self, key): +- if key in self.map: ++ if key in self.map: + key, prev, next = self.map.pop(key) +- prev[1] = next # (the bug) Changed from prev[2] = next to prev[1] = next +- next[2] = prev # (the bug) Changed from next[1] = prev to next[2] = prev ++ prev[2] = next ++ next[1] = prev + + def __iter__(self): + end = self.end +@@ -77,8 +77,8 @@ + + def __eq__(self, other): + if isinstance(other, OrderedSet): +- return len(self) == len(other) and self != other +- return set(self) != set(other) ++ return len(self) == len(other) and list(self) == list(other) ++ return set(self) == set(other) + + + if __name__ == "__main__": +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index c6f9aaf987c5be5e466db737fa7f9a0aee484a61..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -543,9 +543,9 @@ + default_message = "Invalid input." + + def __init__(self, iterable: typing.Iterable, *, error: str | None = None): +- self.iterable = list(iterable) +- self.values_text = " - ".join(str(each) for each in reversed(self.iterable)) +- self.error = self.default_message if error else error ++ self.iterable = iterable ++ self.values_text = ", ".join(str(each) for each in self.iterable) ++ self.error = error or self.default_message # type: str + + def _repr_args(self) -> str: + return f"iterable={self.iterable!r}" +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..05e3a57f78f6b3ac4a72491f235941e080dedd69 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:005c2f29d3e63d99a13080b7e6a8a27d50387c281b917e965322413d3b09affc" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..5ab1d8d5c9fee840e7990130e9b418906ea6c643 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ac6f0dfcc9ad0708b3d99d7d033969cf784d0cb --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/validation/canaries/first-hunk-only.sh @@ -0,0 +1,24 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/orderedset.py b/src/marshmallow/orderedset.py +index 0c039d6be3999b07f48bfc153719cadd3927cc50..7ce0723ac42d747071755d9339c953f4669a0976 100644 +--- a/src/marshmallow/orderedset.py ++++ b/src/marshmallow/orderedset.py +@@ -44,10 +44,10 @@ + curr[2] = end[1] = self.map[key] = [key, curr, end] + + def discard(self, key): +- if key in self.map: ++ if key in self.map: + key, prev, next = self.map.pop(key) +- prev[1] = next # (the bug) Changed from prev[2] = next to prev[1] = next +- next[2] = prev # (the bug) Changed from next[1] = prev to next[2] = prev ++ prev[2] = next ++ next[1] = prev + + def __iter__(self): + end = self.end +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__oa57lis3/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..598bb5190e00b65ff2ba63f18386d10343b15893 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "3824b84675d2724b6431603ac7e7e5043484aecb81d07daeef0b86b615123656", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "841d32961702d21450607bfbf1f49d30e1d36d4cb417c74860c993d2c89b1fd9", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "6a1e3920a6a9a52d5560fa7be3b5e41415c628b9bcb5dfae70aaee89b392ceb3", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "5e9dfa3abd57261f320aab195ec77edf8bc274d7", + "source_completion_sha256": "c916abd4228cf7f2b19f9785534741b42367c1f6a456156160fa83bfef366804", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "1993f59b0deac4dd1c45df689abfefa64f62986b62e49871ca18c029c2f73243", + "is_fork": true, + "learner_path": "tasks/e25ba9b32bc242b2511a693d/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/5e9dfa3abd57261f320aab195ec77edf8bc274d7/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "fc624c52e1ee5c0861a8bfc85efff98f0392ce71c32ce48ea8d01093152ca62e", + "provenance_path": "tasks/e25ba9b32bc242b2511a693d/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "5e9dfa3abd57261f320aab195ec77edf8bc274d7", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "3e6e224fd5479155633c20d2b36024f8ee410228", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at", + "task_sha256": "36b4d330450ec437851cc15360d48ba1d80bd2ae1b5fb000270f5d76020c49f5", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c04874ef696d46c5098c0b5eed7c03b5ac7353e9 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/instruction.md @@ -0,0 +1,46 @@ +Validation decorators and hooks not working correctly + +I'm having issues with field validation and schema processing hooks. The `@validates` decorator seems to be looking for the wrong field name, and the `pass_many` parameter in processing hooks is behaving unexpectedly. + +#### Steps/Code to Reproduce + +```python +from marshmallow import Schema, fields, validates, ValidationError + +class TestSchema(Schema): + foo = fields.String() + + @validates('foo') + def validate_foo(self, value): + if value == 'invalid': + raise ValidationError('Invalid value') + +schema = TestSchema() +# This should work but raises "field does not exist" error +schema.validate({'foo': 'test'}) +``` + +Also having problems with processing hooks: + +```python +from marshmallow import Schema, fields, post_load + +class ProcessorSchema(Schema): + value = fields.Integer() + + @post_load(pass_many=True) + def process_data(self, data, many, **kwargs): + # many parameter seems inverted + print(f"many={many}") + return data + +schema = ProcessorSchema() +# When loading single item, many=True instead of False +result = schema.load({'value': 42}) +``` + +The Predicate validator also seems broken - it's raising validation errors when it should pass and returning None instead of the validated value. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..86165b9a1bf53eb8d0836027b5f6869e70966b7c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "3e6e224fd5479155633c20d2b36024f8ee410228", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "5e9dfa3abd57261f320aab195ec77edf8bc274d7" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_deserialization.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/decorators.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2270919, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "1993f59b0deac4dd1c45df689abfefa64f62986b62e49871ca18c029c2f73243", + "is_fork": true, + "learner_path": "tasks/e25ba9b32bc242b2511a693d/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/5e9dfa3abd57261f320aab195ec77edf8bc274d7/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "fc624c52e1ee5c0861a8bfc85efff98f0392ce71c32ce48ea8d01093152ca62e", + "provenance_path": "tasks/e25ba9b32bc242b2511a693d/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "5e9dfa3abd57261f320aab195ec77edf8bc274d7", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "3e6e224fd5479155633c20d2b36024f8ee410228", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at", + "task_sha256": "36b4d330450ec437851cc15360d48ba1d80bd2ae1b5fb000270f5d76020c49f5", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..3788d01feac30be0a963df8b08dd64a07ce955d6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "3824b84675d2724b6431603ac7e7e5043484aecb81d07daeef0b86b615123656", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/5e9dfa3abd57261f320aab195ec77edf8bc274d7/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "c916abd4228cf7f2b19f9785534741b42367c1f6a456156160fa83bfef366804", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "9784be12599ca3c041270f2b2e2087c7d7e9cba43f62550d912678e6511dff7c", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "1993f59b0deac4dd1c45df689abfefa64f62986b62e49871ca18c029c2f73243", + "is_fork": true, + "learner_path": "tasks/e25ba9b32bc242b2511a693d/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/5e9dfa3abd57261f320aab195ec77edf8bc274d7/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "fc624c52e1ee5c0861a8bfc85efff98f0392ce71c32ce48ea8d01093152ca62e", + "provenance_path": "tasks/e25ba9b32bc242b2511a693d/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "5e9dfa3abd57261f320aab195ec77edf8bc274d7", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "3e6e224fd5479155633c20d2b36024f8ee410228", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at", + "task_sha256": "36b4d330450ec437851cc15360d48ba1d80bd2ae1b5fb000270f5d76020c49f5", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..c139c711cef2689108b25e6080ac5bd029c5c20b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/provided-gold.diff @@ -0,0 +1,57 @@ +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index c439744b9c574370b5e1b07eae50686f3520779b..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -88,7 +88,7 @@ + + :param str field_name: Name of the field that the method validates. + """ +- return set_hook(None, VALIDATES, field_name=field_name[::-1]) ++ return set_hook(None, VALIDATES, field_name=field_name) + + + def validates_schema( +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +@@ -176,7 +176,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, PRE_LOAD, many=not pass_many) ++ return set_hook(fn, PRE_LOAD, many=pass_many) + + + def post_load( +@@ -198,7 +198,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, POST_LOAD, many=not pass_many, pass_original=pass_original) ++ return set_hook(fn, POST_LOAD, many=pass_many, pass_original=pass_original) + + + def set_hook( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 5497b2257b0547add6035399b5ff1fab4aad6d85..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -526,10 +526,10 @@ + def __call__(self, value: typing.Any) -> typing.Any: + method = getattr(value, self.method) + +- if method(**self.kwargs): ++ if not method(**self.kwargs): + raise ValidationError(self._format_error(value)) + +- return None ++ return value + + + class NoneOf(Validator): diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..328b637c66ceff9d05582b0e175a62d094989774 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/solution/solve.sh @@ -0,0 +1,63 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index c439744b9c574370b5e1b07eae50686f3520779b..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -88,7 +88,7 @@ + + :param str field_name: Name of the field that the method validates. + """ +- return set_hook(None, VALIDATES, field_name=field_name[::-1]) ++ return set_hook(None, VALIDATES, field_name=field_name) + + + def validates_schema( +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +@@ -176,7 +176,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, PRE_LOAD, many=not pass_many) ++ return set_hook(fn, PRE_LOAD, many=pass_many) + + + def post_load( +@@ -198,7 +198,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, POST_LOAD, many=not pass_many, pass_original=pass_original) ++ return set_hook(fn, POST_LOAD, many=pass_many, pass_original=pass_original) + + + def set_hook( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 5497b2257b0547add6035399b5ff1fab4aad6d85..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -526,10 +526,10 @@ + def __call__(self, value: typing.Any) -> typing.Any: + method = getattr(value, self.method) + +- if method(**self.kwargs): ++ if not method(**self.kwargs): + raise ValidationError(self._format_error(value)) + +- return None ++ return value + + + class NoneOf(Validator): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7cd53c69e6d27941754a66ed7e0252da214c42d0 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:aaf1c0c86a59813c78903f320be2c640b910b1c79705f6b0b45b80bb7feb82f5" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..d415bdf0f30dbd64f399ab169d3f2816d3814d26 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..466096a90dec7a3d8db1e64532cb8ee5dece56af --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index c439744b9c574370b5e1b07eae50686f3520779b..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -88,7 +88,7 @@ + + :param str field_name: Name of the field that the method validates. + """ +- return set_hook(None, VALIDATES, field_name=field_name[::-1]) ++ return set_hook(None, VALIDATES, field_name=field_name) + + + def validates_schema( +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ojvyn1at/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..0c29fb1c2b7d27c64176d5c0b898d60296e1edcc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "883d932c42f7b43c2d55a5940370cac7e37bb42a50066fc5dfa87dfe4ad9ffc3", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "c3bdfa08aa0499f7b261b99bbf56adab7021981dd7af3a29f6e49ab021fe91d9", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "5123f004b14006252a6dbc0d3326644161328e678ef3bdb2b50f178710c67b84", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "e16d1d4133c3c8d5c145d6810cd4c0f3f5251530", + "source_completion_sha256": "728cebee6a6fe7eadb7767e76ad74dc6108ffba7f1fe7f07c7e7ff9bcc8e5e7f", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "487882352fd8a0478b4adbf94738b9fdaac38e8b0fa4de3d13e3eac4f7be713f", + "is_fork": true, + "learner_path": "tasks/0dc06fee529a6cc1e00dd92f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e16d1d4133c3c8d5c145d6810cd4c0f3f5251530/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "97bf1ca79d1dbe62acce730ce03ff027b733fb9a3442165d3e79e8c5853994a0", + "provenance_path": "tasks/0dc06fee529a6cc1e00dd92f/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e16d1d4133c3c8d5c145d6810cd4c0f3f5251530", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "bc90f9470e499d3082008d65c1b158ced3c220f0", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1", + "task_sha256": "34916de4f124d24d462ba1d73e09fc4574c400ca108fb5c3ba1e03f1915e0dd7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bb0d54b86107748854163b4414dbfa17f6b33e69 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/instruction.md @@ -0,0 +1,46 @@ +OrderedSet discard method corrupts internal structure + +#### Description + +The `OrderedSet.discard()` method appears to be corrupting the internal linked list structure, causing the set to become empty or behave incorrectly after removing elements. + +#### Steps/Code to Reproduce + +```python +from marshmallow.orderedset import OrderedSet + +# Create an OrderedSet with some elements +os = OrderedSet(['a', 'b', 'c']) +print(f"Initial: {os}") # Should show OrderedSet(['a', 'b', 'c']) + +# Remove an element +os.discard('b') +print(f"After discard: {os}") # Shows OrderedSet[] instead of OrderedSet(['a', 'c']) + +# Try iterating +print(f"List: {list(os)}") # Should show ['a', 'c'] but shows [] +``` + +Also affects the `__repr__` method which shows incorrect output format: + +```python +os = OrderedSet(['x', 'y']) +print(repr(os)) # Shows "OrderedSet[]" instead of "OrderedSet(['x', 'y'])" + +empty_os = OrderedSet() +print(repr(empty_os)) # Shows "OrderedSet(['x', 'y'])" instead of "OrderedSet()" +``` + +The equality comparison is also broken: + +```python +os1 = OrderedSet(['a', 'b']) +os2 = OrderedSet(['a', 'b']) +print(os1 == os2) # Should be True but returns False +``` + +This affects schema validation where OrderedSets are used for field filtering, causing unexpected behavior in nested field serialization. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..bc5525e512bd110334f6c63ca8222114ace2f418 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_validate.py::test_predicate_custom_message" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "bc90f9470e499d3082008d65c1b158ced3c220f0", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "e16d1d4133c3c8d5c145d6810cd4c0f3f5251530" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_decorators.py", + "/testbed/tests/test_deserialization.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_fields.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/orderedset.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2277454, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "487882352fd8a0478b4adbf94738b9fdaac38e8b0fa4de3d13e3eac4f7be713f", + "is_fork": true, + "learner_path": "tasks/0dc06fee529a6cc1e00dd92f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e16d1d4133c3c8d5c145d6810cd4c0f3f5251530/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "97bf1ca79d1dbe62acce730ce03ff027b733fb9a3442165d3e79e8c5853994a0", + "provenance_path": "tasks/0dc06fee529a6cc1e00dd92f/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e16d1d4133c3c8d5c145d6810cd4c0f3f5251530", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "bc90f9470e499d3082008d65c1b158ced3c220f0", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1", + "task_sha256": "34916de4f124d24d462ba1d73e09fc4574c400ca108fb5c3ba1e03f1915e0dd7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..a59730b8c7568b66926a9c239c70f2dc23be8098 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "883d932c42f7b43c2d55a5940370cac7e37bb42a50066fc5dfa87dfe4ad9ffc3", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e16d1d4133c3c8d5c145d6810cd4c0f3f5251530/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "728cebee6a6fe7eadb7767e76ad74dc6108ffba7f1fe7f07c7e7ff9bcc8e5e7f", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "43e7937039fa8469dfa38aa6c07629aed69540658391ec7dd2121b57e61de2ae", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "487882352fd8a0478b4adbf94738b9fdaac38e8b0fa4de3d13e3eac4f7be713f", + "is_fork": true, + "learner_path": "tasks/0dc06fee529a6cc1e00dd92f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e16d1d4133c3c8d5c145d6810cd4c0f3f5251530/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "97bf1ca79d1dbe62acce730ce03ff027b733fb9a3442165d3e79e8c5853994a0", + "provenance_path": "tasks/0dc06fee529a6cc1e00dd92f/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e16d1d4133c3c8d5c145d6810cd4c0f3f5251530", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "bc90f9470e499d3082008d65c1b158ced3c220f0", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1", + "task_sha256": "34916de4f124d24d462ba1d73e09fc4574c400ca108fb5c3ba1e03f1915e0dd7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..0546085b502c3e544e494efdc2ab5d2c751673e9 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/provided-gold.diff @@ -0,0 +1,51 @@ +diff --git a/src/marshmallow/orderedset.py b/src/marshmallow/orderedset.py +index 2796ac0568eba1f007e80c188d1977254814aef1..7ce0723ac42d747071755d9339c953f4669a0976 100644 +--- a/src/marshmallow/orderedset.py ++++ b/src/marshmallow/orderedset.py +@@ -44,10 +44,10 @@ + curr[2] = end[1] = self.map[key] = [key, curr, end] + + def discard(self, key): +- if key in self.map: ++ if key in self.map: + key, prev, next = self.map.pop(key) +- prev[1] = next # (the bug) Changed from prev[2] = next to prev[1] = next +- next[2] = prev # (the bug) Changed from next[1] = prev to next[2] = prev ++ prev[2] = next ++ next[1] = prev + + def __iter__(self): + end = self.end +@@ -71,14 +71,14 @@ + return key + + def __repr__(self): +- if self: +- return f"{self.__class__.__name__}[]" +- return f"{self.__class__.__name__}({list(self)})" ++ if not self: ++ return f"{self.__class__.__name__}()" ++ return f"{self.__class__.__name__}({list(self)!r})" + + def __eq__(self, other): + if isinstance(other, OrderedSet): +- return len(self) == len(other) and self != other +- return set(self) != set(other) ++ return len(self) == len(other) and list(self) == list(other) ++ return set(self) == set(other) + + + if __name__ == "__main__": +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 33328c65103bd4454d64065159c7cac54de74e51..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -521,7 +521,7 @@ + return f"method={self.method!r}, kwargs={self.kwargs!r}" + + def _format_error(self, value: typing.Any) -> str: +- return self.error.format(input=self.method, method=value) ++ return self.error.format(input=value, method=self.method) + + def __call__(self, value: typing.Any) -> typing.Any: + method = getattr(value, self.method) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..807e613fbcf183158d307c6648d2e1a4c1039eb3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/solution/solve.sh @@ -0,0 +1,57 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/orderedset.py b/src/marshmallow/orderedset.py +index 2796ac0568eba1f007e80c188d1977254814aef1..7ce0723ac42d747071755d9339c953f4669a0976 100644 +--- a/src/marshmallow/orderedset.py ++++ b/src/marshmallow/orderedset.py +@@ -44,10 +44,10 @@ + curr[2] = end[1] = self.map[key] = [key, curr, end] + + def discard(self, key): +- if key in self.map: ++ if key in self.map: + key, prev, next = self.map.pop(key) +- prev[1] = next # (the bug) Changed from prev[2] = next to prev[1] = next +- next[2] = prev # (the bug) Changed from next[1] = prev to next[2] = prev ++ prev[2] = next ++ next[1] = prev + + def __iter__(self): + end = self.end +@@ -71,14 +71,14 @@ + return key + + def __repr__(self): +- if self: +- return f"{self.__class__.__name__}[]" +- return f"{self.__class__.__name__}({list(self)})" ++ if not self: ++ return f"{self.__class__.__name__}()" ++ return f"{self.__class__.__name__}({list(self)!r})" + + def __eq__(self, other): + if isinstance(other, OrderedSet): +- return len(self) == len(other) and self != other +- return set(self) != set(other) ++ return len(self) == len(other) and list(self) == list(other) ++ return set(self) == set(other) + + + if __name__ == "__main__": +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 33328c65103bd4454d64065159c7cac54de74e51..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -521,7 +521,7 @@ + return f"method={self.method!r}, kwargs={self.kwargs!r}" + + def _format_error(self, value: typing.Any) -> str: +- return self.error.format(input=self.method, method=value) ++ return self.error.format(input=value, method=self.method) + + def __call__(self, value: typing.Any) -> typing.Any: + method = getattr(value, self.method) +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f5f5f984de361da6a5211a71164ab09311e090f4 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:617cf905dd81fb8ebc4122faa6566aff303ff08b72bd3915cd2e23779900c1de" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..cd96bb5f6a1a88e967aeff62484337dde8e0fa0e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_validate.py::test_predicate_custom_message" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..d2a31f4fec30ca2a54f6209af8abb0bf0fe5c6f9 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/validation/canaries/first-hunk-only.sh @@ -0,0 +1,24 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/orderedset.py b/src/marshmallow/orderedset.py +index 2796ac0568eba1f007e80c188d1977254814aef1..7ce0723ac42d747071755d9339c953f4669a0976 100644 +--- a/src/marshmallow/orderedset.py ++++ b/src/marshmallow/orderedset.py +@@ -44,10 +44,10 @@ + curr[2] = end[1] = self.map[key] = [key, curr, end] + + def discard(self, key): +- if key in self.map: ++ if key in self.map: + key, prev, next = self.map.pop(key) +- prev[1] = next # (the bug) Changed from prev[2] = next to prev[1] = next +- next[2] = prev # (the bug) Changed from next[1] = prev to next[2] = prev ++ prev[2] = next ++ next[1] = prev + + def __iter__(self): + end = self.end +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__rt3yxdu1/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..beb2ec7457ec107651bfa9e090ef02f7a8b3f8a8 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "9ffe3fd48fdaec5a1d420c210888a4b2b0ceb159e3df8d811c715094c0f11a33", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "67e1f51d8b9275808f5773e4b5db505ca6f816ab90b0a70fc654e06d3fe8911d", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "23b8531a14124b2507815b172fb1838d808827864cbc874163d8485ad4c49196", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "9fcc20b674911b76ea192bc7a8cd4b4d5c1fb956", + "source_completion_sha256": "c1cb2fe9d3d81d67ab3b9cf9088484d2eab65da93794c57ab5f203d6915d5f84", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "342bccb7479c2cdedde90aff9d07e4f552df10011ef02d911bdf5668d5f737c0", + "is_fork": true, + "learner_path": "tasks/f868b5484e324688563c37d9/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/9fcc20b674911b76ea192bc7a8cd4b4d5c1fb956/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "9648735b39794861f36d1ac8e82246ae86d35b280a237fcf70bc4b980a89827b", + "provenance_path": "tasks/f868b5484e324688563c37d9/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9fcc20b674911b76ea192bc7a8cd4b4d5c1fb956", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f8ba498c0f081e24cc72dd130222012fb0ad8a30", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v", + "task_sha256": "7898d2c8d265ff3870bb6b1db2216909fda3c9adcae568808c9bc754993412f6", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d74751ba6e392b73baa6e36b325e3ec8edb7c0e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/instruction.md @@ -0,0 +1,35 @@ +Email validation fails with UnboundLocalError when checking user part + +#### Description + +The Email validator is throwing an `UnboundLocalError: local variable 'user_part' referenced before assignment` when trying to validate email addresses. This happens because the code tries to use `user_part` before it's defined. + +#### Steps/Code to Reproduce + +```python +from marshmallow import validate + +validator = validate.Email() +validator("test@example.com") +``` + +This should validate the email successfully, but instead raises: + +``` +UnboundLocalError: local variable 'user_part' referenced before assignment +``` + +The same error occurs with any email input, both valid and invalid ones like: +- `"niceandsimple@example.com"` +- `"invalid-email"` +- `"@nouser.com"` +- `""` +- `None` + +#### Expected Behavior + +The Email validator should properly validate email addresses, returning the value for valid emails and raising ValidationError for invalid ones, without any UnboundLocalError. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..5bb2727a79409cdbbf0068ce1e2b863dedf77b74 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "f8ba498c0f081e24cc72dd130222012fb0ad8a30", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "9fcc20b674911b76ea192bc7a8cd4b4d5c1fb956" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_deserialization.py", + "tests/test_options.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/decorators.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2175247, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "342bccb7479c2cdedde90aff9d07e4f552df10011ef02d911bdf5668d5f737c0", + "is_fork": true, + "learner_path": "tasks/f868b5484e324688563c37d9/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/9fcc20b674911b76ea192bc7a8cd4b4d5c1fb956/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "9648735b39794861f36d1ac8e82246ae86d35b280a237fcf70bc4b980a89827b", + "provenance_path": "tasks/f868b5484e324688563c37d9/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9fcc20b674911b76ea192bc7a8cd4b4d5c1fb956", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f8ba498c0f081e24cc72dd130222012fb0ad8a30", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v", + "task_sha256": "7898d2c8d265ff3870bb6b1db2216909fda3c9adcae568808c9bc754993412f6", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..73a83dfce01b44fec31cb00b77f2d2bebdac41df --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "9ffe3fd48fdaec5a1d420c210888a4b2b0ceb159e3df8d811c715094c0f11a33", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/9fcc20b674911b76ea192bc7a8cd4b4d5c1fb956/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "c1cb2fe9d3d81d67ab3b9cf9088484d2eab65da93794c57ab5f203d6915d5f84", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "d58b7b85fec5354e9f3bc057626d518307b143fc507df153b2aab8dcdbcb389e", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "342bccb7479c2cdedde90aff9d07e4f552df10011ef02d911bdf5668d5f737c0", + "is_fork": true, + "learner_path": "tasks/f868b5484e324688563c37d9/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/9fcc20b674911b76ea192bc7a8cd4b4d5c1fb956/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "9648735b39794861f36d1ac8e82246ae86d35b280a237fcf70bc4b980a89827b", + "provenance_path": "tasks/f868b5484e324688563c37d9/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "9fcc20b674911b76ea192bc7a8cd4b4d5c1fb956", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "f8ba498c0f081e24cc72dd130222012fb0ad8a30", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v", + "task_sha256": "7898d2c8d265ff3870bb6b1db2216909fda3c9adcae568808c9bc754993412f6", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..dfacd1453fa9d8f34f57b59ad7d20e6e35d6a005 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/provided-gold.diff @@ -0,0 +1,79 @@ +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 2c15aeae3862347c40406c92f6cdd8ab97336df3..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -119,9 +119,9 @@ + return set_hook( + fn, + VALIDATES_SCHEMA, +- many=pass_original, # Switched 'many' parameter to use 'pass_original' +- pass_original=pass_many, # Switched 'pass_original' to use 'pass_many' +- skip_on_field_errors=not skip_on_field_errors, # Inverted the 'skip_on_field_errors' value ++ many=pass_many, ++ pass_original=pass_original, ++ skip_on_field_errors=skip_on_field_errors, + ) + + +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +@@ -221,14 +221,13 @@ + # Set a __marshmallow_hook__ attribute instead of wrapping in some class, + # because I still want this to end up as a normal (unbound) method. + function = cast(MarshmallowHook, fn) +- hook_config = defaultdict(list) + try: + hook_config = function.__marshmallow_hook__ + except AttributeError: +- function.__marshmallow_hook__ = hook_config ++ function.__marshmallow_hook__ = hook_config = defaultdict(list) + # Also save the kwargs for the tagged function on + # __marshmallow_hook__, keyed by + if hook_config is not None: +- hook_config[tag].append((kwargs, many)) ++ hook_config[tag].append((many, kwargs)) + + return fn +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 8a9c80656d1a1fd48547fc4083caef9ffe2dd0f7..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -256,13 +256,15 @@ + return self.error.format(input=value) + + def __call__(self, value: str) -> str: ++ message = self._format_error(value) ++ ++ if not value or "@" not in value: ++ raise ValidationError(message) ++ ++ user_part, domain_part = value.rsplit("@", 1) + + if not self.USER_REGEX.match(user_part): + raise ValidationError(message) +- +- user_part, domain_part = value.rsplit("@", 1) +- +- return value + + if domain_part not in self.DOMAIN_WHITELIST: + if not self.DOMAIN_REGEX.match(domain_part): +@@ -275,9 +277,8 @@ + return value + raise ValidationError(message) + +- if not value or "@" not in value: +- raise ValidationError(message) +- message = self._format_error(value) ++ return value ++ + + class Range(Validator): + """Validator which succeeds if the value passed to it is within the specified diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..3671318a10b64a4ac53074f7271cb5976c664224 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/solution/solve.sh @@ -0,0 +1,85 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 2c15aeae3862347c40406c92f6cdd8ab97336df3..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -119,9 +119,9 @@ + return set_hook( + fn, + VALIDATES_SCHEMA, +- many=pass_original, # Switched 'many' parameter to use 'pass_original' +- pass_original=pass_many, # Switched 'pass_original' to use 'pass_many' +- skip_on_field_errors=not skip_on_field_errors, # Inverted the 'skip_on_field_errors' value ++ many=pass_many, ++ pass_original=pass_original, ++ skip_on_field_errors=skip_on_field_errors, + ) + + +@@ -138,7 +138,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, PRE_DUMP, many=not pass_many) ++ return set_hook(fn, PRE_DUMP, many=pass_many) + + + def post_dump( +@@ -221,14 +221,13 @@ + # Set a __marshmallow_hook__ attribute instead of wrapping in some class, + # because I still want this to end up as a normal (unbound) method. + function = cast(MarshmallowHook, fn) +- hook_config = defaultdict(list) + try: + hook_config = function.__marshmallow_hook__ + except AttributeError: +- function.__marshmallow_hook__ = hook_config ++ function.__marshmallow_hook__ = hook_config = defaultdict(list) + # Also save the kwargs for the tagged function on + # __marshmallow_hook__, keyed by + if hook_config is not None: +- hook_config[tag].append((kwargs, many)) ++ hook_config[tag].append((many, kwargs)) + + return fn +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 8a9c80656d1a1fd48547fc4083caef9ffe2dd0f7..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -256,13 +256,15 @@ + return self.error.format(input=value) + + def __call__(self, value: str) -> str: ++ message = self._format_error(value) ++ ++ if not value or "@" not in value: ++ raise ValidationError(message) ++ ++ user_part, domain_part = value.rsplit("@", 1) + + if not self.USER_REGEX.match(user_part): + raise ValidationError(message) +- +- user_part, domain_part = value.rsplit("@", 1) +- +- return value + + if domain_part not in self.DOMAIN_WHITELIST: + if not self.DOMAIN_REGEX.match(domain_part): +@@ -275,9 +277,8 @@ + return value + raise ValidationError(message) + +- if not value or "@" not in value: +- raise ValidationError(message) +- message = self._format_error(value) ++ return value ++ + + class Range(Validator): + """Validator which succeeds if the value passed to it is within the specified +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4dd53630142d57908f562df37c0e5197fe7a2ee8 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:f315a5d325104d85098b2e0bb1ffe1bded1425ed1828b5a5a833dd216c75a805" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..675a1eaed9ed64b939daece65691256c54440706 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message" + ], + "pass-to-pass": [ + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..be8cf214ed99ad8ec8de207796a9af2b5a39b424 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/validation/canaries/first-hunk-only.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 2c15aeae3862347c40406c92f6cdd8ab97336df3..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -119,9 +119,9 @@ + return set_hook( + fn, + VALIDATES_SCHEMA, +- many=pass_original, # Switched 'many' parameter to use 'pass_original' +- pass_original=pass_many, # Switched 'pass_original' to use 'pass_many' +- skip_on_field_errors=not skip_on_field_errors, # Inverted the 'skip_on_field_errors' value ++ many=pass_many, ++ pass_original=pass_original, ++ skip_on_field_errors=skip_on_field_errors, + ) + + +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ryii7a1v/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..89ff006829eb0a865e02cd0e0b8ec4ce47513b25 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "3c09dd837850c28a2c11417eb0b1eb128933bc0ccafb5fbf7b9798adc7d6441b", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "c01c2f99bb7d0d283af4cee3573d0e274665e7db16d35d3254d025cfae591871", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "9bde86d69a499893dd5bfaf543502b42ca5e2f3383f9df621c6c9ea59f450545", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "6a8ceda57d703e57ddc410e470028633f70c32aa", + "source_completion_sha256": "f248f383dd2cf9546563b18e9043f91a34902180a203c524365d6be62dcb5550", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "a973d3cb1d61338d61e278671ecd34ab89b4d260ca4bf3f6eb6bfe6a0bbe137e", + "is_fork": true, + "learner_path": "tasks/ef34dd9909f6ce5824916115/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/6a8ceda57d703e57ddc410e470028633f70c32aa/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "328974f97e4fdee742bcdc18073f4cf07c9ca81d45e29f823c7ceea008c7deb4", + "provenance_path": "tasks/ef34dd9909f6ce5824916115/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "6a8ceda57d703e57ddc410e470028633f70c32aa", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "96128470df58ed0299ccb0ff52451ed3ac6f3b5a", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj", + "task_sha256": "d9645155aa8a6d09e490a306ea2ae520e573ba85fe78c11769b511d49bad4f5d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..989539b6664ce6a0c9a9f94d052fbfc9bf724f09 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/instruction.md @@ -0,0 +1,31 @@ +Validator repr format changed unexpectedly + +#### Description + +The string representation of validator objects has changed format. Instead of the expected angle bracket format ``, validators now display with square brackets `[ValidatorName(...)]` and use semicolons instead of commas to separate arguments from the error parameter. + +#### Steps/Code to Reproduce + +```python +from marshmallow import validate + +# Create a simple validator +validator = validate.Email() +print(repr(validator)) + +# Expected: +# Actual: [Email(error='Not a valid email address.')] + +# Also affects other validators +url_validator = validate.URL(relative=False, absolute=True) +print(repr(url_validator)) + +# Expected: +# Actual: [URL(relative=False, absolute=True; error='Not a valid URL.')] +``` + +This affects all validator classes including Range, Length, Equal, Regexp, Predicate, NoneOf, OneOf, and ContainsOnly validators. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..38a9371f9448fc31d968ab573a8def80ea4f588c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_repr" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "96128470df58ed0299ccb0ff52451ed3ac6f3b5a", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "6a8ceda57d703e57ddc410e470028633f70c32aa" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_deserialization.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/decorators.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2270925, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "a973d3cb1d61338d61e278671ecd34ab89b4d260ca4bf3f6eb6bfe6a0bbe137e", + "is_fork": true, + "learner_path": "tasks/ef34dd9909f6ce5824916115/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/6a8ceda57d703e57ddc410e470028633f70c32aa/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "328974f97e4fdee742bcdc18073f4cf07c9ca81d45e29f823c7ceea008c7deb4", + "provenance_path": "tasks/ef34dd9909f6ce5824916115/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "6a8ceda57d703e57ddc410e470028633f70c32aa", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "96128470df58ed0299ccb0ff52451ed3ac6f3b5a", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj", + "task_sha256": "d9645155aa8a6d09e490a306ea2ae520e573ba85fe78c11769b511d49bad4f5d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..6ed7e0f30783f3a0cf768b10c9d724480fbe864b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "3c09dd837850c28a2c11417eb0b1eb128933bc0ccafb5fbf7b9798adc7d6441b", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/6a8ceda57d703e57ddc410e470028633f70c32aa/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "f248f383dd2cf9546563b18e9043f91a34902180a203c524365d6be62dcb5550", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "c8b1e56e531cc05687e0e0bc090644e9d5a58ffed70e1a90786eb4383faeba9b", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "a973d3cb1d61338d61e278671ecd34ab89b4d260ca4bf3f6eb6bfe6a0bbe137e", + "is_fork": true, + "learner_path": "tasks/ef34dd9909f6ce5824916115/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/6a8ceda57d703e57ddc410e470028633f70c32aa/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "328974f97e4fdee742bcdc18073f4cf07c9ca81d45e29f823c7ceea008c7deb4", + "provenance_path": "tasks/ef34dd9909f6ce5824916115/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "6a8ceda57d703e57ddc410e470028633f70c32aa", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "96128470df58ed0299ccb0ff52451ed3ac6f3b5a", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj", + "task_sha256": "d9645155aa8a6d09e490a306ea2ae520e573ba85fe78c11769b511d49bad4f5d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..dc574387adab3276d6ef5927dca636c097796379 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/provided-gold.diff @@ -0,0 +1,38 @@ +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 1625f8b3042258774d2b623d0e64481060c243d0..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -221,14 +221,13 @@ + # Set a __marshmallow_hook__ attribute instead of wrapping in some class, + # because I still want this to end up as a normal (unbound) method. + function = cast(MarshmallowHook, fn) +- hook_config = defaultdict(list) + try: + hook_config = function.__marshmallow_hook__ + except AttributeError: +- function.__marshmallow_hook__ = hook_config ++ function.__marshmallow_hook__ = hook_config = defaultdict(list) + # Also save the kwargs for the tagged function on + # __marshmallow_hook__, keyed by + if hook_config is not None: +- hook_config[tag].append((kwargs, many)) ++ hook_config[tag].append((many, kwargs)) + + return fn +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 4835746af9d6389baeaab2483684578eecb8e914..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -26,9 +26,9 @@ + + def __repr__(self) -> str: + args = self._repr_args() +- args = f"{args}; " if args else "" +- +- return f"[{self.__class__.__name__}({args}error={self.error!r})]" ++ args = f"{args}, " if args else "" ++ ++ return f"<{self.__class__.__name__}({args}error={self.error!r})>" + + def _repr_args(self) -> str: + """A string representation of the args passed to this validator. Used by diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4ba089c39752a950cd8dafaaa7d6eaf3bad85ed1 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/solution/solve.sh @@ -0,0 +1,44 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 1625f8b3042258774d2b623d0e64481060c243d0..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -221,14 +221,13 @@ + # Set a __marshmallow_hook__ attribute instead of wrapping in some class, + # because I still want this to end up as a normal (unbound) method. + function = cast(MarshmallowHook, fn) +- hook_config = defaultdict(list) + try: + hook_config = function.__marshmallow_hook__ + except AttributeError: +- function.__marshmallow_hook__ = hook_config ++ function.__marshmallow_hook__ = hook_config = defaultdict(list) + # Also save the kwargs for the tagged function on + # __marshmallow_hook__, keyed by + if hook_config is not None: +- hook_config[tag].append((kwargs, many)) ++ hook_config[tag].append((many, kwargs)) + + return fn +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 4835746af9d6389baeaab2483684578eecb8e914..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -26,9 +26,9 @@ + + def __repr__(self) -> str: + args = self._repr_args() +- args = f"{args}; " if args else "" +- +- return f"[{self.__class__.__name__}({args}error={self.error!r})]" ++ args = f"{args}, " if args else "" ++ ++ return f"<{self.__class__.__name__}({args}error={self.error!r})>" + + def _repr_args(self) -> str: + """A string representation of the args passed to this validator. Used by +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..eda4d8d0fe369f05a3242136f5adbd523c7585af --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:464e3f3818f88950e289c715ce3875f71d6a2980c936ee4b5e70f5f0f0b9d6f1" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..ce05c7eb8ccc7087e332b0eb01ae51bf029d01ad --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_repr" + ], + "pass-to-pass": [ + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..b615c17cb241878cb4271b02cf9429119762ac6d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/validation/canaries/first-hunk-only.sh @@ -0,0 +1,27 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 1625f8b3042258774d2b623d0e64481060c243d0..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -221,14 +221,13 @@ + # Set a __marshmallow_hook__ attribute instead of wrapping in some class, + # because I still want this to end up as a normal (unbound) method. + function = cast(MarshmallowHook, fn) +- hook_config = defaultdict(list) + try: + hook_config = function.__marshmallow_hook__ + except AttributeError: +- function.__marshmallow_hook__ = hook_config ++ function.__marshmallow_hook__ = hook_config = defaultdict(list) + # Also save the kwargs for the tagged function on + # __marshmallow_hook__, keyed by + if hook_config is not None: +- hook_config[tag].append((kwargs, many)) ++ hook_config[tag].append((many, kwargs)) + + return fn +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__ss70fuvj/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..e201021c59f88900b504b379fc9ebeedc76f5f05 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "559765dfc36411c3917333a2b868145fb112b61c3910a816850df035c0e110bb", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "38ef7300df182ecde4fe1dae9d50f2fb353df1460bb946ad5a4d7cc9b524258d", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "46e53dd4f656f72ed612982c20494efd15ca925400c68ef65c3920363e6bd54d", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "b9acd8a1a14339755a4617862905ac657ca47b99", + "source_completion_sha256": "d6ecea48432dd2e6240c65333e95c31fdb4bfd89239b321fd5a39c00fb6ab931", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "b16bd847f8eb9f9d9724aa33ea8b14ecdc7204d737a3228cc43515e9e1803640", + "is_fork": true, + "learner_path": "tasks/18c0a8b53a8b75b5a4c12486/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/b9acd8a1a14339755a4617862905ac657ca47b99/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "3008a293e893e4acd476305dc219e8d1b2720fef8be98d6c03451cc7d99a6942", + "provenance_path": "tasks/18c0a8b53a8b75b5a4c12486/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b9acd8a1a14339755a4617862905ac657ca47b99", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "61a9f88a539f72161eb7b36e39cbe619e307fdf3", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd", + "task_sha256": "41f39b8b3e649fefc8eece8b6f94787bc242fa4f5c2d2723190c3e9fcb2a4a77", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c41c6a9d67eed79ec41b707376264d78ea8cc216 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/instruction.md @@ -0,0 +1,36 @@ +OneOf validator inverted logic causes validation to fail for valid values + +#### Description + +The OneOf validator is rejecting valid values and accepting invalid ones. When a value is in the allowed choices, it raises a ValidationError instead of passing validation. + +#### Steps/Code to Reproduce + +```python +from marshmallow import validate, ValidationError + +# This should pass but raises ValidationError +validator = validate.OneOf([1, 2, 3]) +try: + result = validator(2) # 2 is in choices, should be valid + print(f"Result: {result}") +except ValidationError as e: + print(f"Unexpected error: {e}") + +# This should fail but doesn't raise an error +try: + result = validator(5) # 5 is not in choices, should raise ValidationError + print(f"Should have failed but got: {result}") +except ValidationError as e: + print(f"Expected error: {e}") +``` + +Expected behavior: Values in the choices list should pass validation, values not in the list should raise ValidationError. + +Actual behavior: Values in the choices list raise ValidationError, values not in the list pass validation. + +Similar issue affects ContainsOnly validator where it's returning truncated results instead of the full validated input. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..bca38e4786e0e881c6d963787aaea52ebf5de242 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "61a9f88a539f72161eb7b36e39cbe619e307fdf3", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "b9acd8a1a14339755a4617862905ac657ca47b99" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_decorators.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_deserialization.py", + "tests/test_registry.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/class_registry.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2206035, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "b16bd847f8eb9f9d9724aa33ea8b14ecdc7204d737a3228cc43515e9e1803640", + "is_fork": true, + "learner_path": "tasks/18c0a8b53a8b75b5a4c12486/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/b9acd8a1a14339755a4617862905ac657ca47b99/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "3008a293e893e4acd476305dc219e8d1b2720fef8be98d6c03451cc7d99a6942", + "provenance_path": "tasks/18c0a8b53a8b75b5a4c12486/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b9acd8a1a14339755a4617862905ac657ca47b99", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "61a9f88a539f72161eb7b36e39cbe619e307fdf3", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd", + "task_sha256": "41f39b8b3e649fefc8eece8b6f94787bc242fa4f5c2d2723190c3e9fcb2a4a77", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..dc2b4c7ff825e4616fed136cf5ce8cef9e24a63f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "559765dfc36411c3917333a2b868145fb112b61c3910a816850df035c0e110bb", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/b9acd8a1a14339755a4617862905ac657ca47b99/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "d6ecea48432dd2e6240c65333e95c31fdb4bfd89239b321fd5a39c00fb6ab931", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "fe339f8d8ceb40c01c816f6eef8bb33ce14c567488a3dd2ecba5f92576f338f5", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "b16bd847f8eb9f9d9724aa33ea8b14ecdc7204d737a3228cc43515e9e1803640", + "is_fork": true, + "learner_path": "tasks/18c0a8b53a8b75b5a4c12486/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/b9acd8a1a14339755a4617862905ac657ca47b99/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "3008a293e893e4acd476305dc219e8d1b2720fef8be98d6c03451cc7d99a6942", + "provenance_path": "tasks/18c0a8b53a8b75b5a4c12486/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "b9acd8a1a14339755a4617862905ac657ca47b99", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "61a9f88a539f72161eb7b36e39cbe619e307fdf3", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd", + "task_sha256": "41f39b8b3e649fefc8eece8b6f94787bc242fa4f5c2d2723190c3e9fcb2a4a77", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..a96e1ced05349aa7b5234e6d2fb12a10def93b0b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/provided-gold.diff @@ -0,0 +1,94 @@ +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index 0db2430b21673dbabc15d8fc315df769b13c8a52..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -26,7 +26,7 @@ + _registry = {} # type: dict[str, list[SchemaType]] + + +-def register(classname: str, cls: SchemaType) ->None: ++def register(classname: str, cls: SchemaType) -> None: + """Add a class to the registry of serializer classes. When a class is + registered, an entry for both its classname and its full, module-qualified + path are added to the registry. +@@ -45,21 +45,29 @@ + # } + + """ +- # Get the fully qualified name (module path + class name) +- module_path = cls.__module__ +- full_path = f"{module_path}.{cls.__name__}" +- +- # Register under the provided class name +- if classname not in _registry: +- _registry[classname] = [] +- if cls not in _registry[classname]: ++ # Module where the class is located ++ module = cls.__module__ ++ # Full module path to the class ++ # e.g. user.schemas.UserSchema ++ fullpath = ".".join([module, classname]) ++ # If the class is already registered; need to check if the entries are ++ # in the same module as cls to avoid having multiple instances of the same ++ # class in the registry ++ if classname in _registry and not any( ++ each.__module__ == module for each in _registry[classname] ++ ): + _registry[classname].append(cls) +- +- # Register under the fully qualified path +- if full_path not in _registry: +- _registry[full_path] = [] +- if cls not in _registry[full_path]: +- _registry[full_path].append(cls) ++ elif classname not in _registry: ++ _registry[classname] = [cls] ++ ++ # Also register the full path ++ if fullpath not in _registry: ++ _registry.setdefault(fullpath, []).append(cls) ++ else: ++ # If fullpath does exist, replace existing entry ++ _registry[fullpath] = [cls] ++ return None ++ + + def get_class(classname: str, all: bool = False) -> list[SchemaType] | SchemaType: + """Retrieve a class from the registry. +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 064366fc76914b9d51e6ab7a6b559d7701bc8fb9..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -597,12 +597,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value in self.choices: ++ if value not in self.choices: + raise ValidationError(self._format_error(value)) +- except TypeError: +- pass +- +- return None ++ except TypeError as error: ++ raise ValidationError(self._format_error(value)) from error ++ ++ return value + + def options( + self, +@@ -647,11 +647,11 @@ + return super()._format_error(value_text) + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: +- reversed_choices = list(reversed(self.choices)) ++ # We can't use set.issubset because does not handle unhashable types + for val in value: +- if val not in reversed_choices: ++ if val not in self.choices: + raise ValidationError(self._format_error(value)) +- return value[:-1] ++ return value + + + class ContainsNoneOf(NoneOf): diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b2205bca20231c715817174d3fce5156064d9f75 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/solution/solve.sh @@ -0,0 +1,100 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index 0db2430b21673dbabc15d8fc315df769b13c8a52..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -26,7 +26,7 @@ + _registry = {} # type: dict[str, list[SchemaType]] + + +-def register(classname: str, cls: SchemaType) ->None: ++def register(classname: str, cls: SchemaType) -> None: + """Add a class to the registry of serializer classes. When a class is + registered, an entry for both its classname and its full, module-qualified + path are added to the registry. +@@ -45,21 +45,29 @@ + # } + + """ +- # Get the fully qualified name (module path + class name) +- module_path = cls.__module__ +- full_path = f"{module_path}.{cls.__name__}" +- +- # Register under the provided class name +- if classname not in _registry: +- _registry[classname] = [] +- if cls not in _registry[classname]: ++ # Module where the class is located ++ module = cls.__module__ ++ # Full module path to the class ++ # e.g. user.schemas.UserSchema ++ fullpath = ".".join([module, classname]) ++ # If the class is already registered; need to check if the entries are ++ # in the same module as cls to avoid having multiple instances of the same ++ # class in the registry ++ if classname in _registry and not any( ++ each.__module__ == module for each in _registry[classname] ++ ): + _registry[classname].append(cls) +- +- # Register under the fully qualified path +- if full_path not in _registry: +- _registry[full_path] = [] +- if cls not in _registry[full_path]: +- _registry[full_path].append(cls) ++ elif classname not in _registry: ++ _registry[classname] = [cls] ++ ++ # Also register the full path ++ if fullpath not in _registry: ++ _registry.setdefault(fullpath, []).append(cls) ++ else: ++ # If fullpath does exist, replace existing entry ++ _registry[fullpath] = [cls] ++ return None ++ + + def get_class(classname: str, all: bool = False) -> list[SchemaType] | SchemaType: + """Retrieve a class from the registry. +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 064366fc76914b9d51e6ab7a6b559d7701bc8fb9..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -597,12 +597,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value in self.choices: ++ if value not in self.choices: + raise ValidationError(self._format_error(value)) +- except TypeError: +- pass +- +- return None ++ except TypeError as error: ++ raise ValidationError(self._format_error(value)) from error ++ ++ return value + + def options( + self, +@@ -647,11 +647,11 @@ + return super()._format_error(value_text) + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: +- reversed_choices = list(reversed(self.choices)) ++ # We can't use set.issubset because does not handle unhashable types + for val in value: +- if val not in reversed_choices: ++ if val not in self.choices: + raise ValidationError(self._format_error(value)) +- return value[:-1] ++ return value + + + class ContainsNoneOf(NoneOf): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..143edba58b9f14d0234fe490c2e8bb3ccc6f53ac --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:268deb3fab1a1a76d19102bb21994ca23b5aafe929fe73845e01ad6a67313c17" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..41b727ba8ee126bdc30f6358f10cdb5cae21918e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..65a05b5fadc24f09b8403beb59b6128b741fcc96 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index 0db2430b21673dbabc15d8fc315df769b13c8a52..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -26,7 +26,7 @@ + _registry = {} # type: dict[str, list[SchemaType]] + + +-def register(classname: str, cls: SchemaType) ->None: ++def register(classname: str, cls: SchemaType) -> None: + """Add a class to the registry of serializer classes. When a class is + registered, an entry for both its classname and its full, module-qualified + path are added to the registry. +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__tes1m6pd/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..a351a766fa882a071ff3f18ab7bdcfdc8ba59e98 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "c9e6038e8a2e3e7c8681cec9c5ec621111e8008c0d0f1f2a4225c7be92cc1ffe", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "773ae49d522f2019f02ca34a796fb3d21e6c5ea6ef15fd3e4755ef567caf2259", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "3038aed2ebf4948d2edb2b7417735d3b85196aeb56e89ad12da367297b3b5636", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "1f4d9be6f3cebbbe0844bb548f15b0e2331fc429", + "source_completion_sha256": "6c7a2cee3a271350372c7147589b57b08be69a96046b3671b470cb1ff125f0a0", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "10b4969327722186e3cb80b3b87d63aa86e6dfae815e81c0a63efaa6f8b7e351", + "is_fork": true, + "learner_path": "tasks/3cedf115fb0478665b8c5044/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/1f4d9be6f3cebbbe0844bb548f15b0e2331fc429/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "26f9e6351911c25a7cd504a34e15214ae8c2253ac5b796b96587e28bd8ca5729", + "provenance_path": "tasks/3cedf115fb0478665b8c5044/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "1f4d9be6f3cebbbe0844bb548f15b0e2331fc429", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ff89b9378954b7d14f3b538a7d62a2566d9c56e3", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd", + "task_sha256": "48d98c7401907c5c5ef4abc70726352d1aedb35b3cf32b56244fd056ac5c1d68", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d728c95f36e4307c60c72de0c98b958ce0a9e6e9 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/instruction.md @@ -0,0 +1,46 @@ +post_dump decorator arguments swapped causing TypeError + +#### Description + +The `post_dump` decorator has its arguments swapped internally, causing `TypeError` when using `pass_many` and `pass_original` parameters. Methods decorated with `@post_dump(pass_many=True, pass_original=True)` receive incorrect argument mappings. + +#### Steps/Code to Reproduce + +```python +from marshmallow import Schema, fields +from marshmallow.decorators import post_dump + +class TestSchema(Schema): + value = fields.Int() + + @post_dump(pass_many=True, pass_original=True) + def add_metadata(self, data, original_data, many, **kwargs): + # This should work but raises TypeError + return data + +schema = TestSchema() +result = schema.dump({'value': 42}) +``` + +Also affects validation with `Equal` validator: + +```python +from marshmallow import Schema, fields +from marshmallow.validate import Equal + +class ValidationSchema(Schema): + flag = fields.Raw(validate=Equal(False)) + +schema = ValidationSchema() +errors = schema.validate({'flag': True}) +print(errors) # Expected: {'flag': ['Must be equal to False.']} + # Actual: {'flag': ['']} +``` + +The issue manifests as: +- `TypeError: got multiple values for argument 'many'` when using post_dump with both pass_many and pass_original +- Empty error messages from Equal validator instead of proper validation messages + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..65ae809af3d1860f72072e5490ea94c5f8ae516f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_validate.py::test_equal_repr" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "ff89b9378954b7d14f3b538a7d62a2566d9c56e3", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "1f4d9be6f3cebbbe0844bb548f15b0e2331fc429" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_schema.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_deserialization.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/decorators.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2275611, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "10b4969327722186e3cb80b3b87d63aa86e6dfae815e81c0a63efaa6f8b7e351", + "is_fork": true, + "learner_path": "tasks/3cedf115fb0478665b8c5044/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/1f4d9be6f3cebbbe0844bb548f15b0e2331fc429/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "26f9e6351911c25a7cd504a34e15214ae8c2253ac5b796b96587e28bd8ca5729", + "provenance_path": "tasks/3cedf115fb0478665b8c5044/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "1f4d9be6f3cebbbe0844bb548f15b0e2331fc429", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ff89b9378954b7d14f3b538a7d62a2566d9c56e3", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd", + "task_sha256": "48d98c7401907c5c5ef4abc70726352d1aedb35b3cf32b56244fd056ac5c1d68", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..60d7773e5c53139348823568da2fa6425ef31181 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "c9e6038e8a2e3e7c8681cec9c5ec621111e8008c0d0f1f2a4225c7be92cc1ffe", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/1f4d9be6f3cebbbe0844bb548f15b0e2331fc429/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "6c7a2cee3a271350372c7147589b57b08be69a96046b3671b470cb1ff125f0a0", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "2a044fdd64bcdc167695d4999b1489e645b5e2e4025696dbdd2f6fccb3972ced", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "10b4969327722186e3cb80b3b87d63aa86e6dfae815e81c0a63efaa6f8b7e351", + "is_fork": true, + "learner_path": "tasks/3cedf115fb0478665b8c5044/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/1f4d9be6f3cebbbe0844bb548f15b0e2331fc429/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "26f9e6351911c25a7cd504a34e15214ae8c2253ac5b796b96587e28bd8ca5729", + "provenance_path": "tasks/3cedf115fb0478665b8c5044/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "1f4d9be6f3cebbbe0844bb548f15b0e2331fc429", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "ff89b9378954b7d14f3b538a7d62a2566d9c56e3", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd", + "task_sha256": "48d98c7401907c5c5ef4abc70726352d1aedb35b3cf32b56244fd056ac5c1d68", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..d0ab55238ccc4795c384dcd62fe92dc0d374172b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/provided-gold.diff @@ -0,0 +1,28 @@ +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 3f441a2b66896d9d528ef932d93a22e8a2ad9c52..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -159,7 +159,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, POST_DUMP, many=pass_original, pass_original=pass_many) ++ return set_hook(fn, POST_DUMP, many=pass_many, pass_original=pass_original) + + + def pre_load( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 0c14218481fee6a3cca54e0b4edccf014536ccca..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -435,8 +435,8 @@ + default_message = "Must be equal to {other}." + + def __init__(self, comparable, *, error: str | None = None): +- self.comparable = None if comparable is None else comparable +- self.error = error if error else "" ++ self.comparable = comparable ++ self.error = error or self.default_message # type: str + + def _repr_args(self) -> str: + return f"comparable={self.comparable!r}" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..9865bca737b27cbe00bf572e577bb597433748f4 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/solution/solve.sh @@ -0,0 +1,34 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 3f441a2b66896d9d528ef932d93a22e8a2ad9c52..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -159,7 +159,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, POST_DUMP, many=pass_original, pass_original=pass_many) ++ return set_hook(fn, POST_DUMP, many=pass_many, pass_original=pass_original) + + + def pre_load( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 0c14218481fee6a3cca54e0b4edccf014536ccca..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -435,8 +435,8 @@ + default_message = "Must be equal to {other}." + + def __init__(self, comparable, *, error: str | None = None): +- self.comparable = None if comparable is None else comparable +- self.error = error if error else "" ++ self.comparable = comparable ++ self.error = error or self.default_message # type: str + + def _repr_args(self) -> str: + return f"comparable={self.comparable!r}" +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6d2179baa825d0e43f0bac08de41286465c2ca75 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:dea0cc8b7e995b61261e9ca1cf084560659f81ba80ef315dd03fdcce832f9395" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..c79ee7824ca4c93ff56ed58b0a19fae0630c042f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_validate.py::test_equal_repr" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..daf13fe46d5fd58146300726b3f662c45dab547a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 3f441a2b66896d9d528ef932d93a22e8a2ad9c52..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -159,7 +159,7 @@ + .. versionchanged:: 3.0.0 + ``many`` is always passed as a keyword arguments to the decorated method. + """ +- return set_hook(fn, POST_DUMP, many=pass_original, pass_original=pass_many) ++ return set_hook(fn, POST_DUMP, many=pass_many, pass_original=pass_original) + + + def pre_load( +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__u1f3hzvd/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..613fde006e7513599709c8e5479cddbe92a38875 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "999ec5ca7fd0e7dcf7f6432a4ab2fdea8e17772f7af4b99346cfafe5e22aecb7", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "fae28ffc7991921c36c4e9f2790ab942ad2e9af3655fe5dc5850ad8bd96ba2a8", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "9764430a21dbe2e5383e14069cbd5fb6470229181b20d48ee047fc99cd7ca069", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "fcfc4809fd2066c451d50d5e6b45c1e0e9cade99", + "source_completion_sha256": "6742c6de414e36c63db4e513d118d49e77a15eca51697d813349b3223fd38a32", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "7c7fbfbc5141692555933f8f6df2aac1844fb4a7422df720d08298c473b05196", + "is_fork": true, + "learner_path": "tasks/a9212381549bc8b1ea1684d5/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/fcfc4809fd2066c451d50d5e6b45c1e0e9cade99/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "62d3c2d2a064e6b96dd1a0e4387f192de6e2db36a7b93b3b7710551f4e59ea32", + "provenance_path": "tasks/a9212381549bc8b1ea1684d5/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "fcfc4809fd2066c451d50d5e6b45c1e0e9cade99", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e575f676631b3e3a65620fc583734b47186c7fb9", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc", + "task_sha256": "8bf2b090c4b161921876e8e1c7a50854291401082eb325ebbd62488b28be88b9", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d5d65f1928a31d913521d59e3c0eeb89a18163cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/instruction.md @@ -0,0 +1,43 @@ +# ContainsOnly validator returns truncated sequences and reverses choice order + +## Description + +I found a bug in the `ContainsOnly` validator that causes two issues: + +1. It returns a truncated sequence (removing the last element) instead of the original sequence +2. It reverses the order of choices when checking if values are valid + +For example: + +```python +from marshmallow.validate import ContainsOnly + +# This should return [1, 2, 3] but returns [1, 2] instead +result = ContainsOnly([1, 2, 3])([1, 2, 3]) +print(result) # Output: [1, 2] + +# This should work but fails because choices are reversed +validator = ContainsOnly([1, 2, 3, 4]) +try: + validator([1]) # This fails if 1 is not in the first positions of the reversed choices +except Exception as e: + print(f"Error: {e}") +``` + +The issue affects all sequence types (lists, tuples, strings): + +```python +# String example +result = ContainsOnly("abc")("abc") +print(result) # Returns "ab" instead of "abc" + +# Tuple example +result = ContainsOnly((1, 2, 3))((1, 2, 3)) +print(result) # Returns (1, 2) instead of (1, 2, 3) +``` + +This is particularly problematic when using the validator in schemas, as it silently truncates data without any error. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..618f18a90f16c9ae97f1d8870ec6c6da68184aa5 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "e575f676631b3e3a65620fc583734b47186c7fb9", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "fcfc4809fd2066c451d50d5e6b45c1e0e9cade99" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_decorators.py", + "/testbed/tests/test_deserialization.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_schema.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_registry.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/class_registry.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2387719, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "7c7fbfbc5141692555933f8f6df2aac1844fb4a7422df720d08298c473b05196", + "is_fork": true, + "learner_path": "tasks/a9212381549bc8b1ea1684d5/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/fcfc4809fd2066c451d50d5e6b45c1e0e9cade99/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "62d3c2d2a064e6b96dd1a0e4387f192de6e2db36a7b93b3b7710551f4e59ea32", + "provenance_path": "tasks/a9212381549bc8b1ea1684d5/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "fcfc4809fd2066c451d50d5e6b45c1e0e9cade99", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e575f676631b3e3a65620fc583734b47186c7fb9", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc", + "task_sha256": "8bf2b090c4b161921876e8e1c7a50854291401082eb325ebbd62488b28be88b9", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..a33833eaf73434ce4595e296e4b7da1645ea37b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "999ec5ca7fd0e7dcf7f6432a4ab2fdea8e17772f7af4b99346cfafe5e22aecb7", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/fcfc4809fd2066c451d50d5e6b45c1e0e9cade99/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "6742c6de414e36c63db4e513d118d49e77a15eca51697d813349b3223fd38a32", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "5f9e55e4564ab7605dcd87111e3bd4fdc65ed645e3382424c432367c87741daa", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "7c7fbfbc5141692555933f8f6df2aac1844fb4a7422df720d08298c473b05196", + "is_fork": true, + "learner_path": "tasks/a9212381549bc8b1ea1684d5/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/fcfc4809fd2066c451d50d5e6b45c1e0e9cade99/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "62d3c2d2a064e6b96dd1a0e4387f192de6e2db36a7b93b3b7710551f4e59ea32", + "provenance_path": "tasks/a9212381549bc8b1ea1684d5/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "fcfc4809fd2066c451d50d5e6b45c1e0e9cade99", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e575f676631b3e3a65620fc583734b47186c7fb9", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc", + "task_sha256": "8bf2b090c4b161921876e8e1c7a50854291401082eb325ebbd62488b28be88b9", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..a2e5b0219b9ca32a21419d9978a72abc8933f844 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/provided-gold.diff @@ -0,0 +1,38 @@ +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index bc0fc4b4194085ca72e72e79e6f6052a9ec27ac3..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -62,11 +62,12 @@ + + # Also register the full path + if fullpath not in _registry: ++ _registry.setdefault(fullpath, []).append(cls) ++ else: + # If fullpath does exist, replace existing entry + _registry[fullpath] = [cls] +- else: +- _registry.setdefault(fullpath, []).append(cls) + return None ++ + + def get_class(classname: str, all: bool = False) -> list[SchemaType] | SchemaType: + """Retrieve a class from the registry. +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index a51e9a73097e22fa24f7036f32e2f748f80791f5..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -647,11 +647,11 @@ + return super()._format_error(value_text) + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: +- reversed_choices = list(reversed(self.choices)) ++ # We can't use set.issubset because does not handle unhashable types + for val in value: +- if val not in reversed_choices: ++ if val not in self.choices: + raise ValidationError(self._format_error(value)) +- return value[:-1] ++ return value + + + class ContainsNoneOf(NoneOf): diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..07e5eb92e60e8c0657ffe7823e9b2458a8267baf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/solution/solve.sh @@ -0,0 +1,44 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index bc0fc4b4194085ca72e72e79e6f6052a9ec27ac3..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -62,11 +62,12 @@ + + # Also register the full path + if fullpath not in _registry: ++ _registry.setdefault(fullpath, []).append(cls) ++ else: + # If fullpath does exist, replace existing entry + _registry[fullpath] = [cls] +- else: +- _registry.setdefault(fullpath, []).append(cls) + return None ++ + + def get_class(classname: str, all: bool = False) -> list[SchemaType] | SchemaType: + """Retrieve a class from the registry. +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index a51e9a73097e22fa24f7036f32e2f748f80791f5..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -647,11 +647,11 @@ + return super()._format_error(value_text) + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: +- reversed_choices = list(reversed(self.choices)) ++ # We can't use set.issubset because does not handle unhashable types + for val in value: +- if val not in reversed_choices: ++ if val not in self.choices: + raise ValidationError(self._format_error(value)) +- return value[:-1] ++ return value + + + class ContainsNoneOf(NoneOf): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d7bc54b12eb29631b90440731df1703c2a600e0c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:c3319a6ee0a18cec2721f2059447793447b5f16c79141fa03c317bbf9f727c00" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..b47fda7169bc465a590e69da17e2620b27c0535e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..f76f52bd966a47292a5b861fde8172c41d4907e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/validation/canaries/first-hunk-only.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index bc0fc4b4194085ca72e72e79e6f6052a9ec27ac3..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -62,11 +62,12 @@ + + # Also register the full path + if fullpath not in _registry: ++ _registry.setdefault(fullpath, []).append(cls) ++ else: + # If fullpath does exist, replace existing entry + _registry[fullpath] = [cls] +- else: +- _registry.setdefault(fullpath, []).append(cls) + return None ++ + + def get_class(classname: str, all: bool = False) -> list[SchemaType] | SchemaType: + """Retrieve a class from the registry. +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wfo404sc/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..eb67923e4d55f679684600d560a69dc63a379ebe --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "23fca0fdb2520563b31e02bced0870572a0d9d184f4a671237bddaf040621392", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "ece9afb7acc0b1be0cd5adf687e41feff95041e78937459879101c12f6899678", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "932c2903e750294a0c225f962209e4c6074ec803308c2d1062aff158dd510e95", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "e17da4dfde1757a13e2abf22d9dbc9921cfcfa07", + "source_completion_sha256": "e324355323fa0c52acb4472e10aa3d5e02f40552d38afb5593c7f1b9ca54dcf6", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "74d0a3cce6565914aed5e497ec266fe4c20e6ae521180c4fd6ff4a9459f16b1c", + "is_fork": true, + "learner_path": "tasks/8c9c9a80bdc1bee5b5db2f04/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e17da4dfde1757a13e2abf22d9dbc9921cfcfa07/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "eb17f86ee760512697c9b91c93ca0975ff2ca8dc59c513cbe468d7c621c8d4c2", + "provenance_path": "tasks/8c9c9a80bdc1bee5b5db2f04/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e17da4dfde1757a13e2abf22d9dbc9921cfcfa07", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "adb44578fddf93d81b66a9472d9aabc69839cfc2", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0", + "task_sha256": "c2b58d6a7cac432501ec8624650a98b06cc829d8a4d92f26e57d789bc7f8f73e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7e4f449d600f20736f9fb94376dee940aff046de --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/instruction.md @@ -0,0 +1,57 @@ +Validation logic inverted in multiple validators + +#### Description + +Several validators are behaving opposite to their expected behavior. The OneOf validator is rejecting valid values that should be accepted, and the Predicate validator is accepting values that should be rejected. + +#### Steps/Code to Reproduce + +```python +from marshmallow import validate, ValidationError + +# OneOf validator rejecting valid choices +validator = validate.OneOf([1, 2, 3]) +try: + result = validator(2) # Should pass but raises ValidationError + print(f"OneOf result: {result}") +except ValidationError as e: + print(f"OneOf error: {e}") + +# Predicate validator accepting invalid values +class TestObj: + def is_false(self): + return False + +obj = TestObj() +predicate_validator = validate.Predicate('is_false') +try: + result = predicate_validator(obj) # Should raise ValidationError but passes + print(f"Predicate result: {result}") +except ValidationError as e: + print(f"Predicate error: {e}") + +# ContainsOnly validator returning truncated results +contains_validator = validate.ContainsOnly([1, 2, 3]) +result = contains_validator([1, 2]) # Should return [1, 2] but returns [1] +print(f"ContainsOnly result: {result}") +``` + +Expected output: +``` +OneOf result: 2 +Predicate error: Invalid input. +ContainsOnly result: [1, 2] +``` + +Actual output: +``` +OneOf error: Must be one of: 1, 2, 3. +Predicate result: None +ContainsOnly result: [1] +``` + +The validators seem to have their validation logic inverted - they're failing when they should pass and passing when they should fail. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..e41900efd981430521566d9dd7d612272ca8acfc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "adb44578fddf93d81b66a9472d9aabc69839cfc2", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "e17da4dfde1757a13e2abf22d9dbc9921cfcfa07" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_decorators.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_deserialization.py", + "tests/test_registry.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/class_registry.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2204881, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "74d0a3cce6565914aed5e497ec266fe4c20e6ae521180c4fd6ff4a9459f16b1c", + "is_fork": true, + "learner_path": "tasks/8c9c9a80bdc1bee5b5db2f04/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e17da4dfde1757a13e2abf22d9dbc9921cfcfa07/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "eb17f86ee760512697c9b91c93ca0975ff2ca8dc59c513cbe468d7c621c8d4c2", + "provenance_path": "tasks/8c9c9a80bdc1bee5b5db2f04/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e17da4dfde1757a13e2abf22d9dbc9921cfcfa07", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "adb44578fddf93d81b66a9472d9aabc69839cfc2", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0", + "task_sha256": "c2b58d6a7cac432501ec8624650a98b06cc829d8a4d92f26e57d789bc7f8f73e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..1c78e34861e921f70f1bca7697b8051837bbfc37 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "23fca0fdb2520563b31e02bced0870572a0d9d184f4a671237bddaf040621392", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e17da4dfde1757a13e2abf22d9dbc9921cfcfa07/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "e324355323fa0c52acb4472e10aa3d5e02f40552d38afb5593c7f1b9ca54dcf6", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "98913da2f0819f1c5f368fda507fd447b81f79fb8d5aac2ab49409290e692607", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "74d0a3cce6565914aed5e497ec266fe4c20e6ae521180c4fd6ff4a9459f16b1c", + "is_fork": true, + "learner_path": "tasks/8c9c9a80bdc1bee5b5db2f04/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e17da4dfde1757a13e2abf22d9dbc9921cfcfa07/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "eb17f86ee760512697c9b91c93ca0975ff2ca8dc59c513cbe468d7c621c8d4c2", + "provenance_path": "tasks/8c9c9a80bdc1bee5b5db2f04/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e17da4dfde1757a13e2abf22d9dbc9921cfcfa07", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "adb44578fddf93d81b66a9472d9aabc69839cfc2", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0", + "task_sha256": "c2b58d6a7cac432501ec8624650a98b06cc829d8a4d92f26e57d789bc7f8f73e", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..d7b06e87c951da914a22efc7d993da79d407fefe --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/provided-gold.diff @@ -0,0 +1,144 @@ +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index b6b2e3196a99beac9f6b8a0903149f39514c74a4..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -27,20 +27,45 @@ + + + def register(classname: str, cls: SchemaType) -> None: ++ """Add a class to the registry of serializer classes. When a class is ++ registered, an entry for both its classname and its full, module-qualified ++ path are added to the registry. ++ ++ Example: :: ++ ++ class MyClass: ++ pass ++ ++ ++ register("MyClass", MyClass) ++ # Registry: ++ # { ++ # 'MyClass': [path.to.MyClass], ++ # 'path.to.MyClass': [path.to.MyClass], ++ # } ++ ++ """ ++ # Module where the class is located + module = cls.__module__ ++ # Full module path to the class ++ # e.g. user.schemas.UserSchema + fullpath = ".".join([module, classname]) +- +- if classname in _registry and any( ++ # If the class is already registered; need to check if the entries are ++ # in the same module as cls to avoid having multiple instances of the same ++ # class in the registry ++ if classname in _registry and not any( + each.__module__ == module for each in _registry[classname] + ): +- del _registry[classname] ++ _registry[classname].append(cls) + elif classname not in _registry: + _registry[classname] = [cls] + ++ # Also register the full path + if fullpath not in _registry: ++ _registry.setdefault(fullpath, []).append(cls) ++ else: ++ # If fullpath does exist, replace existing entry + _registry[fullpath] = [cls] +- else: +- _registry[fullpath].append(cls) + return None + + +@@ -52,17 +77,18 @@ + """ + try: + classes = _registry[classname] +- except KeyError: ++ except KeyError as error: + raise RegistryError( + f"Class with name {classname!r} was not found. You may need " + "to import the class." +- ) ++ ) from error + if len(classes) > 1: +- if not all: ++ if all: + return _registry[classname] + raise RegistryError( + f"Multiple classes with name {classname!r} " + "were found. Please use the full, " + "module-qualified path." + ) +- return classes[-1] ++ else: ++ return _registry[classname][0] +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index f36c7947fe1a06d2d45c71c16c6a2d5a9fe6a564..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -163,12 +163,12 @@ + def __call__( + self, relative: bool, absolute: bool, require_tld: bool + ) -> typing.Pattern: +- key = (absolute, relative, require_tld) ++ key = (relative, absolute, require_tld) + if key not in self._memoized: + self._memoized[key] = self._regex_generator( +- relative, absolute, not require_tld ++ relative, absolute, require_tld + ) +- ++ + return self._memoized[key] + + _regex = RegexMemoizer() +@@ -526,10 +526,10 @@ + def __call__(self, value: typing.Any) -> typing.Any: + method = getattr(value, self.method) + +- if method(**self.kwargs): ++ if not method(**self.kwargs): + raise ValidationError(self._format_error(value)) + +- return None ++ return value + + + class NoneOf(Validator): +@@ -597,12 +597,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value in self.choices: ++ if value not in self.choices: + raise ValidationError(self._format_error(value)) +- except TypeError: +- pass +- +- return None ++ except TypeError as error: ++ raise ValidationError(self._format_error(value)) from error ++ ++ return value + + def options( + self, +@@ -647,11 +647,11 @@ + return super()._format_error(value_text) + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: +- reversed_choices = list(reversed(self.choices)) ++ # We can't use set.issubset because does not handle unhashable types + for val in value: +- if val not in reversed_choices: ++ if val not in self.choices: + raise ValidationError(self._format_error(value)) +- return value[:-1] ++ return value + + + class ContainsNoneOf(NoneOf): diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a10485617daa5a406cdf7b30ad5a6432bad9e454 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/solution/solve.sh @@ -0,0 +1,150 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index b6b2e3196a99beac9f6b8a0903149f39514c74a4..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -27,20 +27,45 @@ + + + def register(classname: str, cls: SchemaType) -> None: ++ """Add a class to the registry of serializer classes. When a class is ++ registered, an entry for both its classname and its full, module-qualified ++ path are added to the registry. ++ ++ Example: :: ++ ++ class MyClass: ++ pass ++ ++ ++ register("MyClass", MyClass) ++ # Registry: ++ # { ++ # 'MyClass': [path.to.MyClass], ++ # 'path.to.MyClass': [path.to.MyClass], ++ # } ++ ++ """ ++ # Module where the class is located + module = cls.__module__ ++ # Full module path to the class ++ # e.g. user.schemas.UserSchema + fullpath = ".".join([module, classname]) +- +- if classname in _registry and any( ++ # If the class is already registered; need to check if the entries are ++ # in the same module as cls to avoid having multiple instances of the same ++ # class in the registry ++ if classname in _registry and not any( + each.__module__ == module for each in _registry[classname] + ): +- del _registry[classname] ++ _registry[classname].append(cls) + elif classname not in _registry: + _registry[classname] = [cls] + ++ # Also register the full path + if fullpath not in _registry: ++ _registry.setdefault(fullpath, []).append(cls) ++ else: ++ # If fullpath does exist, replace existing entry + _registry[fullpath] = [cls] +- else: +- _registry[fullpath].append(cls) + return None + + +@@ -52,17 +77,18 @@ + """ + try: + classes = _registry[classname] +- except KeyError: ++ except KeyError as error: + raise RegistryError( + f"Class with name {classname!r} was not found. You may need " + "to import the class." +- ) ++ ) from error + if len(classes) > 1: +- if not all: ++ if all: + return _registry[classname] + raise RegistryError( + f"Multiple classes with name {classname!r} " + "were found. Please use the full, " + "module-qualified path." + ) +- return classes[-1] ++ else: ++ return _registry[classname][0] +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index f36c7947fe1a06d2d45c71c16c6a2d5a9fe6a564..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -163,12 +163,12 @@ + def __call__( + self, relative: bool, absolute: bool, require_tld: bool + ) -> typing.Pattern: +- key = (absolute, relative, require_tld) ++ key = (relative, absolute, require_tld) + if key not in self._memoized: + self._memoized[key] = self._regex_generator( +- relative, absolute, not require_tld ++ relative, absolute, require_tld + ) +- ++ + return self._memoized[key] + + _regex = RegexMemoizer() +@@ -526,10 +526,10 @@ + def __call__(self, value: typing.Any) -> typing.Any: + method = getattr(value, self.method) + +- if method(**self.kwargs): ++ if not method(**self.kwargs): + raise ValidationError(self._format_error(value)) + +- return None ++ return value + + + class NoneOf(Validator): +@@ -597,12 +597,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value in self.choices: ++ if value not in self.choices: + raise ValidationError(self._format_error(value)) +- except TypeError: +- pass +- +- return None ++ except TypeError as error: ++ raise ValidationError(self._format_error(value)) from error ++ ++ return value + + def options( + self, +@@ -647,11 +647,11 @@ + return super()._format_error(value_text) + + def __call__(self, value: typing.Sequence[_T]) -> typing.Sequence[_T]: +- reversed_choices = list(reversed(self.choices)) ++ # We can't use set.issubset because does not handle unhashable types + for val in value: +- if val not in reversed_choices: ++ if val not in self.choices: + raise ValidationError(self._format_error(value)) +- return value[:-1] ++ return value + + + class ContainsNoneOf(NoneOf): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9a381ce16bd35682b9e4d6fb13e88955778d29fd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:6eb6a8248c0c42cbf1d1d713ebb85e6786caa4328613cc0b02942b27fa354fad" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..5dc0725aee5c7a8299401cbea80c83f82270a572 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..345f35d091632f1f5fa84175cc5ed668a656b75f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/validation/canaries/first-hunk-only.sh @@ -0,0 +1,61 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index b6b2e3196a99beac9f6b8a0903149f39514c74a4..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -27,20 +27,45 @@ + + + def register(classname: str, cls: SchemaType) -> None: ++ """Add a class to the registry of serializer classes. When a class is ++ registered, an entry for both its classname and its full, module-qualified ++ path are added to the registry. ++ ++ Example: :: ++ ++ class MyClass: ++ pass ++ ++ ++ register("MyClass", MyClass) ++ # Registry: ++ # { ++ # 'MyClass': [path.to.MyClass], ++ # 'path.to.MyClass': [path.to.MyClass], ++ # } ++ ++ """ ++ # Module where the class is located + module = cls.__module__ ++ # Full module path to the class ++ # e.g. user.schemas.UserSchema + fullpath = ".".join([module, classname]) +- +- if classname in _registry and any( ++ # If the class is already registered; need to check if the entries are ++ # in the same module as cls to avoid having multiple instances of the same ++ # class in the registry ++ if classname in _registry and not any( + each.__module__ == module for each in _registry[classname] + ): +- del _registry[classname] ++ _registry[classname].append(cls) + elif classname not in _registry: + _registry[classname] = [cls] + ++ # Also register the full path + if fullpath not in _registry: ++ _registry.setdefault(fullpath, []).append(cls) ++ else: ++ # If fullpath does exist, replace existing entry + _registry[fullpath] = [cls] +- else: +- _registry[fullpath].append(cls) + return None + + +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__wv2v45s0/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..21a5414679e47f10d643955ed0d5ba07c36a560a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "85e63e4335707ad17d986a6f1b65124b9f46db28d466f44cb29694f53f73fda7", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "339c67e045eb3751c863cc9c81966aa6716d505f397345731efa8de3577b1136", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "7a983b5e0da68a8e3b4a3a477d99df4dc0192d6e5dc0f2a8a570566dd5cfc570", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "668df442dc2216bd8bb08edf7cc2216db386a75a", + "source_completion_sha256": "ae41bca81f964fd20fb31ff247cc77dee5b3fd7c53345517b3bed3733a1586ed", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "5a3eb9c723525326acb27d4d50f6ddbf95c8b46d4d12fc981301b08d2b344dd9", + "is_fork": true, + "learner_path": "tasks/b9ab1a1d0f2467b62318f75e/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/668df442dc2216bd8bb08edf7cc2216db386a75a/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "26ae4bfad578e60bdee198c8231bca643e2bc45d20047579b08dca2ed74559de", + "provenance_path": "tasks/b9ab1a1d0f2467b62318f75e/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "668df442dc2216bd8bb08edf7cc2216db386a75a", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "53a0d486334601e23af7a8528c704aa4815f28ad", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0", + "task_sha256": "8d08d49ab0f3310407b7137c2bc9862b331ad78a309a356d274c9d18e05c91a5", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..47a6cf37050e4d6898c8977cec7bef971f755a65 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/instruction.md @@ -0,0 +1,44 @@ +# Two issues with Regexp validator and post_load decorator + +## Issue 1: Regexp validator returns None instead of the validated value + +When using the Regexp validator, it's returning None instead of the validated value. This breaks validation chains and causes unexpected behavior. + +```python +from marshmallow import Schema, fields, validate + +class MySchema(Schema): + name = fields.String(validate=validate.Regexp('[a-z]+')) + +schema = MySchema() +result = schema.load({"name": "test"}) +print(result) # Expected: {"name": "test"}, but getting {"name": None} +``` + +## Issue 2: post_load decorator not working correctly with pass_many parameter + +The post_load decorator seems to be inverting the pass_many parameter, causing errors when processing data. This is breaking schemas that use post_load with specific pass_many settings. + +```python +from marshmallow import Schema, fields, post_load + +class UserSchema(Schema): + name = fields.String() + + @post_load(pass_many=True) + def make_user(self, data, many, **kwargs): + # This function is not receiving the correct 'many' value + # and data is not in the expected format + print(f"Data: {data}, Many: {many}") + return data + +schema = UserSchema() +result = schema.load([{"name": "John"}, {"name": "Jane"}], many=True) +# Getting TypeError: list indices must be integers or slices, not str +``` + +I've also noticed that the Regexp validator is now using search() instead of match(), which changes the validation behavior. The match() method checks if the pattern matches at the beginning of the string, while search() looks for the pattern anywhere in the string. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..67211719e3dc7494970cf62a6a417eb0bfba446a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "53a0d486334601e23af7a8528c704aa4815f28ad", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "668df442dc2216bd8bb08edf7cc2216db386a75a" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_deserialization.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/decorators.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2270901, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "5a3eb9c723525326acb27d4d50f6ddbf95c8b46d4d12fc981301b08d2b344dd9", + "is_fork": true, + "learner_path": "tasks/b9ab1a1d0f2467b62318f75e/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/668df442dc2216bd8bb08edf7cc2216db386a75a/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "26ae4bfad578e60bdee198c8231bca643e2bc45d20047579b08dca2ed74559de", + "provenance_path": "tasks/b9ab1a1d0f2467b62318f75e/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "668df442dc2216bd8bb08edf7cc2216db386a75a", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "53a0d486334601e23af7a8528c704aa4815f28ad", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0", + "task_sha256": "8d08d49ab0f3310407b7137c2bc9862b331ad78a309a356d274c9d18e05c91a5", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..cf6a28203a6cfff3f46552489b73add26cc5ce43 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "85e63e4335707ad17d986a6f1b65124b9f46db28d466f44cb29694f53f73fda7", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/668df442dc2216bd8bb08edf7cc2216db386a75a/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "ae41bca81f964fd20fb31ff247cc77dee5b3fd7c53345517b3bed3733a1586ed", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "db2ad36b6a894b713a9647312ee26aaac9f3df7f92a5b41bed6e6844e82d5282", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "5a3eb9c723525326acb27d4d50f6ddbf95c8b46d4d12fc981301b08d2b344dd9", + "is_fork": true, + "learner_path": "tasks/b9ab1a1d0f2467b62318f75e/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/668df442dc2216bd8bb08edf7cc2216db386a75a/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "26ae4bfad578e60bdee198c8231bca643e2bc45d20047579b08dca2ed74559de", + "provenance_path": "tasks/b9ab1a1d0f2467b62318f75e/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "668df442dc2216bd8bb08edf7cc2216db386a75a", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "53a0d486334601e23af7a8528c704aa4815f28ad", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0", + "task_sha256": "8d08d49ab0f3310407b7137c2bc9862b331ad78a309a356d274c9d18e05c91a5", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..a3e54ef7db136ab0dda5fcda61c2c26d25c16573 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/provided-gold.diff @@ -0,0 +1,30 @@ +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index b4d07443dcb704f6b0ee912a28663a29582d7f04..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -198,7 +198,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, POST_LOAD, many=not pass_many, pass_original=pass_original) ++ return set_hook(fn, POST_LOAD, many=pass_many, pass_original=pass_original) + + + def set_hook( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 489c4cb30d8d306502dd5150b5a1d52d34045ec7..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -492,10 +492,10 @@ + def __call__(self, value: bytes) -> bytes: ... + + def __call__(self, value): +- if self.regex.search(value) is None: ++ if self.regex.match(value) is None: + raise ValidationError(self._format_error(value)) + +- return None ++ return value + + + class Predicate(Validator): diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e5351091cec3d6f7f9c293f772f617012f39437e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/solution/solve.sh @@ -0,0 +1,36 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index b4d07443dcb704f6b0ee912a28663a29582d7f04..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -198,7 +198,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, POST_LOAD, many=not pass_many, pass_original=pass_original) ++ return set_hook(fn, POST_LOAD, many=pass_many, pass_original=pass_original) + + + def set_hook( +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 489c4cb30d8d306502dd5150b5a1d52d34045ec7..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -492,10 +492,10 @@ + def __call__(self, value: bytes) -> bytes: ... + + def __call__(self, value): +- if self.regex.search(value) is None: ++ if self.regex.match(value) is None: + raise ValidationError(self._format_error(value)) + +- return None ++ return value + + + class Predicate(Validator): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..abec40d944a922f47e6b0df525075ab56187cff3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:3b087a10b3721f5cc5ffba642ed6070ec1427e81dcd4437b968afec80d1a30ac" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..e24ed6fa9aa03a6e2fc82403e4c7130ebbe2a904 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..8b2977d463a0c91ea54239fcd2f61756f47fc75a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index b4d07443dcb704f6b0ee912a28663a29582d7f04..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -198,7 +198,7 @@ + ``partial`` and ``many`` are always passed as keyword arguments to + the decorated method. + """ +- return set_hook(fn, POST_LOAD, many=not pass_many, pass_original=pass_original) ++ return set_hook(fn, POST_LOAD, many=pass_many, pass_original=pass_original) + + + def set_hook( +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__x8v7o8e0/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..198a7f9ea7b7958f91cf089c1535757d7fdf4c9f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "4100a38f9888a3e11cca3ebf1a9eea78cf8021cae8085e0c316f3fec4c3aafc1", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "efa81fa90328ac970d4168e2ba634785112dee9ab5b58e0c2ed1658f11f1eabc", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "8e1b0b789a5a58c12079fbc18ec751089215151042f7e8c62124830b61fb9975", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "e9441d67ad224358810323eea062df041b1bc772", + "source_completion_sha256": "cdece12796111cb4583890b0beefbe74a0ce6e134ba2d8f8cb03663639c3847a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "2c1c580cf5f07c10e78808a4efc008b226dc562f7edb75e3f5f801a0175d53f8", + "is_fork": true, + "learner_path": "tasks/0531c58429557dde7f6625ac/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e9441d67ad224358810323eea062df041b1bc772/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "9d38b0819465ce158b2e163488e37b9149f3a265c00ce157832eac9cdb3d0a33", + "provenance_path": "tasks/0531c58429557dde7f6625ac/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e9441d67ad224358810323eea062df041b1bc772", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e802605e212b39eedbedb9e847898ca7c8b489ba", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l", + "task_sha256": "2b5822970a39be041365b1b3e0d1fa1c1d8cb8df01bd641bd008fd17c86ce106", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a06b65f7eff77f58c3156b0b87f3c18b4b444a6c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/instruction.md @@ -0,0 +1,36 @@ +OneOf validator returns None instead of validated value + +#### Description + +The OneOf validator is not working correctly - it's returning None instead of the validated value when validation passes, and it's raising ValidationError when the value IS in the choices list instead of when it's NOT in the choices list. + +#### Steps/Code to Reproduce + +```python +from marshmallow import validate + +# This should return 2, but returns None +validator = validate.OneOf([1, 2, 3]) +result = validator(2) +print(f"Expected: 2, Got: {result}") + +# This should pass without error, but raises ValidationError +try: + validate.OneOf([1, 2, 3])(2) + print("Should not raise error") +except Exception as e: + print(f"Unexpected error: {e}") + +# This should raise ValidationError, but passes +try: + validate.OneOf([1, 2, 3])(4) + print("Should have raised ValidationError") +except Exception as e: + print(f"Expected error: {e}") +``` + +The validator logic seems to be inverted - it's validating when values are IN the choices instead of when they're NOT in the choices. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..ffc6dd737108d243dbb6e82b880069811ce55dc3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_custom_message" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "e802605e212b39eedbedb9e847898ca7c8b489ba", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "e9441d67ad224358810323eea062df041b1bc772" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_decorators.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_deserialization.py", + "tests/test_registry.py", + "tests/test_schema.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/class_registry.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2206655, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "2c1c580cf5f07c10e78808a4efc008b226dc562f7edb75e3f5f801a0175d53f8", + "is_fork": true, + "learner_path": "tasks/0531c58429557dde7f6625ac/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e9441d67ad224358810323eea062df041b1bc772/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "9d38b0819465ce158b2e163488e37b9149f3a265c00ce157832eac9cdb3d0a33", + "provenance_path": "tasks/0531c58429557dde7f6625ac/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e9441d67ad224358810323eea062df041b1bc772", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e802605e212b39eedbedb9e847898ca7c8b489ba", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l", + "task_sha256": "2b5822970a39be041365b1b3e0d1fa1c1d8cb8df01bd641bd008fd17c86ce106", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..4e0fb353c69aca53410b73609fd88d9aff3ab4d4 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "4100a38f9888a3e11cca3ebf1a9eea78cf8021cae8085e0c316f3fec4c3aafc1", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e9441d67ad224358810323eea062df041b1bc772/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "cdece12796111cb4583890b0beefbe74a0ce6e134ba2d8f8cb03663639c3847a", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "c4205de5beb6f5b56f75c109d3f88da8d0fdb14d4ffd5348feec61f900e0c943", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "2c1c580cf5f07c10e78808a4efc008b226dc562f7edb75e3f5f801a0175d53f8", + "is_fork": true, + "learner_path": "tasks/0531c58429557dde7f6625ac/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e9441d67ad224358810323eea062df041b1bc772/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "9d38b0819465ce158b2e163488e37b9149f3a265c00ce157832eac9cdb3d0a33", + "provenance_path": "tasks/0531c58429557dde7f6625ac/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e9441d67ad224358810323eea062df041b1bc772", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e802605e212b39eedbedb9e847898ca7c8b489ba", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l", + "task_sha256": "2b5822970a39be041365b1b3e0d1fa1c1d8cb8df01bd641bd008fd17c86ce106", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..13760961795bb75530e6dc8430b5219285497b03 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/provided-gold.diff @@ -0,0 +1,43 @@ +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index bbaeba004268d3c389f417ab71c28ecb34e11052..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -83,12 +83,12 @@ + "to import the class." + ) from error + if len(classes) > 1: +- return _registry[classname][0] +- else: + if all: + return _registry[classname] + raise RegistryError( + f"Multiple classes with name {classname!r} " + "were found. Please use the full, " + "module-qualified path." +- ) +\ No newline at end of file ++ ) ++ else: ++ return _registry[classname][0] +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 905cc1ac023df62cd82a6f960674d1afb164d1c3..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -597,12 +597,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value in self.choices: ++ if value not in self.choices: + raise ValidationError(self._format_error(value)) +- except TypeError: +- pass +- +- return None ++ except TypeError as error: ++ raise ValidationError(self._format_error(value)) from error ++ ++ return value + + def options( + self, diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..8d9ba8e844fb70a08fb7dac490609da0000e131c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/solution/solve.sh @@ -0,0 +1,49 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index bbaeba004268d3c389f417ab71c28ecb34e11052..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -83,12 +83,12 @@ + "to import the class." + ) from error + if len(classes) > 1: +- return _registry[classname][0] +- else: + if all: + return _registry[classname] + raise RegistryError( + f"Multiple classes with name {classname!r} " + "were found. Please use the full, " + "module-qualified path." +- ) +\ No newline at end of file ++ ) ++ else: ++ return _registry[classname][0] +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 905cc1ac023df62cd82a6f960674d1afb164d1c3..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -597,12 +597,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value in self.choices: ++ if value not in self.choices: + raise ValidationError(self._format_error(value)) +- except TypeError: +- pass +- +- return None ++ except TypeError as error: ++ raise ValidationError(self._format_error(value)) from error ++ ++ return value + + def options( + self, +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6d5b14c3ccaef7e6fda42bd6b4ec5f3bcaa4a9b2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:1e3373b28bcfe0f89e7093d8480d27f77f324907f923ba46fda98d9c6d572701" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..8052253932612bb2175fa06d1330f527b657ec16 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_custom_message" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..4138251f2ed79a40f29272f64a5f95fc67fa7198 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/validation/canaries/first-hunk-only.sh @@ -0,0 +1,27 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/class_registry.py b/src/marshmallow/class_registry.py +index bbaeba004268d3c389f417ab71c28ecb34e11052..d41b112e67d49a6b7514dfb4d62a05eb58edc497 100644 +--- a/src/marshmallow/class_registry.py ++++ b/src/marshmallow/class_registry.py +@@ -83,12 +83,12 @@ + "to import the class." + ) from error + if len(classes) > 1: +- return _registry[classname][0] +- else: + if all: + return _registry[classname] + raise RegistryError( + f"Multiple classes with name {classname!r} " + "were found. Please use the full, " + "module-qualified path." +- ) +\ No newline at end of file ++ ) ++ else: ++ return _registry[classname][0] +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__z086q78l/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..0c8d03c1da6d910c53b285abd856220239b784e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "c8a64aa0dac19497d978452c6c346ec9d33bc491b6eda558de50612aec423180", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "538a5489d877fee1d04b2338f7d004e0606a4d0d0e5439cfedad9845120289f4", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "07b72f61339f5399a6a7d5352ada48f9635e3a0489bb37f1361b33291e982453", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "ab3d2e5719824fd63f78f39c40381404a6332145", + "source_completion_sha256": "c548b1872296fe105721713e1128b25557985b62482a9ab3e350bc7373daaad8", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "d9c6338f0d6615f38eacaf19fa173a87cc8083b4437e3b47b1b3681fd78a54c7", + "is_fork": true, + "learner_path": "tasks/3f8802b0de9f6728bfe80774/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ab3d2e5719824fd63f78f39c40381404a6332145/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "a8f12624e1201dfc517c38c9e07c49e371f23c265e471f971b79ea84134559f4", + "provenance_path": "tasks/3f8802b0de9f6728bfe80774/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ab3d2e5719824fd63f78f39c40381404a6332145", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "7ec9831ef0d1e0ca203ba7c8d16cd1a16e6e8840", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn", + "task_sha256": "2b9f194581ac73a1076ff18b9563449e9e1907a4c35d0ce0d25b45c52577d407", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5ad532b2162c605575ceac3b1159240a39a49aaf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/instruction.md @@ -0,0 +1,41 @@ +NoneOf validator returns None instead of value and validates incorrectly + +#### Description + +The `NoneOf` validator is not working as expected. It's returning `None` for all inputs instead of the original value, and the validation logic appears to be inverted. + +#### Steps/Code to Reproduce + +```python +from marshmallow import validate + +# This should return 4 but returns None +validator = validate.NoneOf([1, 2, 3]) +result = validator(4) +print(f"Expected: 4, Got: {result}") + +# This should raise ValidationError but doesn't +try: + validator(3) # 3 is in the forbidden list + print("ERROR: Should have raised ValidationError") +except validate.ValidationError: + print("Correctly raised ValidationError") + +# String example +string_validator = validate.NoneOf('abc') +result = string_validator('d') +print(f"Expected: 'd', Got: {result}") +``` + +Expected behavior: +- `NoneOf([1, 2, 3])(4)` should return `4` +- `NoneOf([1, 2, 3])(3)` should raise `ValidationError` +- `NoneOf('abc')('d')` should return `'d'` + +Actual behavior: +- All valid inputs return `None` instead of the original value +- Invalid inputs (values that should be rejected) don't raise ValidationError + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..d389af72e6411421ac0c9b0c776f0a2d9aa895fb --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/metadata.json @@ -0,0 +1,1399 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "7ec9831ef0d1e0ca203ba7c8d16cd1a16e6e8840", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "ab3d2e5719824fd63f78f39c40381404a6332145" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_deserialization.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_fields.py", + "/testbed/tests/test_options.py", + "/testbed/tests/test_registry.py", + "/testbed/tests/test_schema.py", + "/testbed/tests/test_serialization.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_validate.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/decorators.py", + "src/marshmallow/validate.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2364031, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "d9c6338f0d6615f38eacaf19fa173a87cc8083b4437e3b47b1b3681fd78a54c7", + "is_fork": true, + "learner_path": "tasks/3f8802b0de9f6728bfe80774/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ab3d2e5719824fd63f78f39c40381404a6332145/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "a8f12624e1201dfc517c38c9e07c49e371f23c265e471f971b79ea84134559f4", + "provenance_path": "tasks/3f8802b0de9f6728bfe80774/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ab3d2e5719824fd63f78f39c40381404a6332145", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "7ec9831ef0d1e0ca203ba7c8d16cd1a16e6e8840", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn", + "task_sha256": "2b9f194581ac73a1076ff18b9563449e9e1907a4c35d0ce0d25b45c52577d407", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..f4ea9f78b1d7a14cf24b7033da5153e24ad74218 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "c8a64aa0dac19497d978452c6c346ec9d33bc491b6eda558de50612aec423180", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ab3d2e5719824fd63f78f39c40381404a6332145/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "c548b1872296fe105721713e1128b25557985b62482a9ab3e350bc7373daaad8", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "12bb14af2d53b444926831438fad80b969103f653e5b05a6fa4c48ed5b12338e", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "d9c6338f0d6615f38eacaf19fa173a87cc8083b4437e3b47b1b3681fd78a54c7", + "is_fork": true, + "learner_path": "tasks/3f8802b0de9f6728bfe80774/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/ab3d2e5719824fd63f78f39c40381404a6332145/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "a8f12624e1201dfc517c38c9e07c49e371f23c265e471f971b79ea84134559f4", + "provenance_path": "tasks/3f8802b0de9f6728bfe80774/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "ab3d2e5719824fd63f78f39c40381404a6332145", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "7ec9831ef0d1e0ca203ba7c8d16cd1a16e6e8840", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn", + "task_sha256": "2b9f194581ac73a1076ff18b9563449e9e1907a4c35d0ce0d25b45c52577d407", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..97da660e0ef1309a71b2815edfb9f5408305b078 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/provided-gold.diff @@ -0,0 +1,38 @@ +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 472ca20aa2b752d66487fb23d2708c95347a141d..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -119,9 +119,9 @@ + return set_hook( + fn, + VALIDATES_SCHEMA, +- many=pass_original, # Switched 'many' parameter to use 'pass_original' +- pass_original=pass_many, # Switched 'pass_original' to use 'pass_many' +- skip_on_field_errors=not skip_on_field_errors, # Inverted the 'skip_on_field_errors' value ++ many=pass_many, ++ pass_original=pass_original, ++ skip_on_field_errors=skip_on_field_errors, + ) + + +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 056698435d6fa17210986bf255301c4793137763..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -555,12 +555,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value not in self.iterable: ++ if value in self.iterable: + raise ValidationError(self._format_error(value)) + except TypeError: +- return None +- +- return None ++ pass ++ ++ return value + + + class OneOf(Validator): diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a72cfa82fe704d232b55b9fd44c27c7f5d167cd9 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/solution/solve.sh @@ -0,0 +1,44 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 472ca20aa2b752d66487fb23d2708c95347a141d..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -119,9 +119,9 @@ + return set_hook( + fn, + VALIDATES_SCHEMA, +- many=pass_original, # Switched 'many' parameter to use 'pass_original' +- pass_original=pass_many, # Switched 'pass_original' to use 'pass_many' +- skip_on_field_errors=not skip_on_field_errors, # Inverted the 'skip_on_field_errors' value ++ many=pass_many, ++ pass_original=pass_original, ++ skip_on_field_errors=skip_on_field_errors, + ) + + +diff --git a/src/marshmallow/validate.py b/src/marshmallow/validate.py +index 056698435d6fa17210986bf255301c4793137763..e4536d88c4d4481e82c21d8757436653e59577e5 100644 +--- a/src/marshmallow/validate.py ++++ b/src/marshmallow/validate.py +@@ -555,12 +555,12 @@ + + def __call__(self, value: typing.Any) -> typing.Any: + try: +- if value not in self.iterable: ++ if value in self.iterable: + raise ValidationError(self._format_error(value)) + except TypeError: +- return None +- +- return None ++ pass ++ ++ return value + + + class OneOf(Validator): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2f56d34929b621287fc711c19a89ed909821aae3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:78c3b4d4ccfc5efef876b96134414d156f50ce4c8e1ffea85b27beb1e75607af" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..39b1356925b3bee3591d937d6b6238b299b32c05 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/expected-panels.json @@ -0,0 +1,1194 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_naive_datetime_field", + "tests/test_schema.py::test_datetime_formatted_field", + "tests/test_schema.py::test_datetime_iso_field", + "tests/test_schema.py::test_tz_datetime_field", + "tests/test_schema.py::test_class_variable", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_custom_field", + "tests/test_schema.py::test_url_field", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_method_field[UserSchema]", + "tests/test_schema.py::test_method_field[UserMetaSchema]", + "tests/test_schema.py::test_function_field", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_can_serialize_uuid", + "tests/test_schema.py::test_can_serialize_time", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/validation/canaries/first-hunk-only.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..66652dfb83c8eee76bbc53e66137ca995951fead --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/validation/canaries/first-hunk-only.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/marshmallow/decorators.py b/src/marshmallow/decorators.py +index 472ca20aa2b752d66487fb23d2708c95347a141d..965edb68b7ddd2eeaba41aa49e51d2dd7c2440db 100644 +--- a/src/marshmallow/decorators.py ++++ b/src/marshmallow/decorators.py +@@ -119,9 +119,9 @@ + return set_hook( + fn, + VALIDATES_SCHEMA, +- many=pass_original, # Switched 'many' parameter to use 'pass_original' +- pass_original=pass_many, # Switched 'pass_original' to use 'pass_many' +- skip_on_field_errors=not skip_on_field_errors, # Inverted the 'skip_on_field_errors' value ++ many=pass_many, ++ pass_original=pass_original, ++ skip_on_field_errors=skip_on_field_errors, + ) + + +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.combine_module__zv4fhthn/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/LICENSE.source b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..b20df7cab259cfce3d02bd8da515ce65870612b7 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/LICENSE.source @@ -0,0 +1,19 @@ +Copyright Steven Loria and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/adapter.json b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..e431096e3e56c1254d53390d9fd7671d1e6478e9 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "62d8a53bdf6361dcd6d058029baf7da1087f768e422c9ec25687c790aa028fe2", + "gold_patch_sha256": "01f5059a524fa9d0aa01dc811a8155e6431d3665b2044959074cbf33760493c0", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "c66cd365eb98ed5851132f687c76d4a787ed99e69198287233f5a967cbd2b541", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": false, + "partial_repair_sha256": null, + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/marshmallow-code__marshmallow.9716fc62.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "e2c64ac7b3290c2cfe1effeb7a5c46ccf9c6136e", + "source_completion_sha256": "9a68076b7e01ab52fe11b05d504d69daf10efce2fbd07c8b5fd051ea38a6408b", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "11b545421a29cd553e770b1af92727ea50261cc9da430998fc31b5031211ecaa", + "is_fork": true, + "learner_path": "tasks/86db919f95f8fdc838e23d36/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e2c64ac7b3290c2cfe1effeb7a5c46ccf9c6136e/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "a4867104b545e0cffa07cc71b471773f8a9216db78009bdd1c9f1421c3a0ebaf", + "provenance_path": "tasks/86db919f95f8fdc838e23d36/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e2c64ac7b3290c2cfe1effeb7a5c46ccf9c6136e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "966b1127e3d07b4f906620046a02f46be1ffb70b", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70", + "task_sha256": "03d4ac79223320b7a23aa87a735459968b463cf1457f4ea492c5e9fd057bde56", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "symlink_submodule_changes_supported": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "marshmallow-code/marshmallow" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/dependency-setup.sh b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..35a236d9370f89c608fd6e358f7a6d2b90ce6f0a --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/dependency-setup.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install -e . +python -m pip install -e '.[tests]' diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/environment/Dockerfile b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/instruction.md b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bb403a03adaa5d015cbb998d55ed9490e1a5c436 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/instruction.md @@ -0,0 +1,30 @@ +Schema.get_value() method has incorrect parameter order + +#### Description + +The `get_value()` method in the Schema class is passing parameters in the wrong order to the underlying `get_value()` function, causing serialization to fail with various TypeError messages. + +#### Steps/Code to Reproduce + +```python +from marshmallow import Schema, fields + +class User: + def __init__(self, name): + self.name = name + +class UserSchema(Schema): + name = fields.Str() + +user = User('John') +schema = UserSchema() +result = schema.dump(user) +``` + +This raises a `TypeError: getattr(): attribute name must be string` or similar errors depending on the field type and object structure. + +The issue affects basic serialization operations where the schema tries to extract values from objects using the `get_value()` method. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/metadata.json b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..282245aad470fafd2d6f5d0eba5380512cdf6369 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/metadata.json @@ -0,0 +1,1384 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator" + ], + "PASS_TO_PASS": [ + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "966b1127e3d07b4f906620046a02f46be1ffb70b", + "healthy": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "learner": "e2c64ac7b3290c2cfe1effeb7a5c46ccf9c6136e" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/FUNDING.yml", + "/testbed/.github/dependabot.yml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/.readthedocs.yml", + "/testbed/AUTHORS.rst", + "/testbed/CHANGELOG.rst", + "/testbed/CODE_OF_CONDUCT.md", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/NOTICE", + "/testbed/README.rst", + "/testbed/RELEASING.md", + "/testbed/SECURITY.md", + "/testbed/docs/.gitignore", + "/testbed/docs/_static/css/sponsor-message.css", + "/testbed/docs/_static/css/versionwarning.css", + "/testbed/docs/_static/marshmallow-logo.png", + "/testbed/docs/_templates/donate.html", + "/testbed/docs/_templates/useful-links.html", + "/testbed/docs/about.rst.inc", + "/testbed/docs/api_reference.rst", + "/testbed/docs/authors.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/code_of_conduct.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contributing.rst", + "/testbed/docs/custom_fields.rst", + "/testbed/docs/dashing.json", + "/testbed/docs/ecosystem.rst", + "/testbed/docs/examples.rst", + "/testbed/docs/extending.rst", + "/testbed/docs/index.rst", + "/testbed/docs/install.rst", + "/testbed/docs/kudos.rst", + "/testbed/docs/license.rst", + "/testbed/docs/marshmallow.class_registry.rst", + "/testbed/docs/marshmallow.decorators.rst", + "/testbed/docs/marshmallow.error_store.rst", + "/testbed/docs/marshmallow.exceptions.rst", + "/testbed/docs/marshmallow.fields.rst", + "/testbed/docs/marshmallow.schema.rst", + "/testbed/docs/marshmallow.utils.rst", + "/testbed/docs/marshmallow.validate.rst", + "/testbed/docs/nesting.rst", + "/testbed/docs/quickstart.rst", + "/testbed/docs/upgrading.rst", + "/testbed/docs/whos_using.rst", + "/testbed/docs/why.rst", + "/testbed/examples/flask_example.py", + "/testbed/examples/inflection_example.py", + "/testbed/examples/package_json_example.py", + "/testbed/examples/peewee_example.py", + "/testbed/examples/textblob_example.py", + "/testbed/performance/benchmark.py", + "/testbed/pyproject.toml", + "/testbed/src/marshmallow/__init__.py", + "/testbed/src/marshmallow/base.py", + "/testbed/src/marshmallow/class_registry.py", + "/testbed/src/marshmallow/decorators.py", + "/testbed/src/marshmallow/error_store.py", + "/testbed/src/marshmallow/exceptions.py", + "/testbed/src/marshmallow/fields.py", + "/testbed/src/marshmallow/orderedset.py", + "/testbed/src/marshmallow/py.typed", + "/testbed/src/marshmallow/schema.py", + "/testbed/src/marshmallow/types.py", + "/testbed/src/marshmallow/utils.py", + "/testbed/src/marshmallow/validate.py", + "/testbed/src/marshmallow/warnings.py", + "/testbed/tests/__init__.py", + "/testbed/tests/base.py", + "/testbed/tests/conftest.py", + "/testbed/tests/foo_serializer.py", + "/testbed/tests/mypy_test_cases/test_validation_error.py", + "/testbed/tests/test_error_store.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_utils.py", + "/testbed/tests/test_validate.py", + "/testbed/tests/test_version_attributes.py", + "/testbed/tox.ini" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Marshmallow9716fc62", + "profile_lines": [ + 542, + 545 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "private_test_paths": [ + "tests/test_decorators.py", + "tests/test_deserialization.py", + "tests/test_fields.py", + "tests/test_options.py", + "tests/test_registry.py", + "tests/test_schema.py", + "tests/test_serialization.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/marshmallow/schema.py" + ], + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_stages_bytes": 2137025, + "task_id": "marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "marshmallow-code/marshmallow" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "11b545421a29cd553e770b1af92727ea50261cc9da430998fc31b5031211ecaa", + "is_fork": true, + "learner_path": "tasks/86db919f95f8fdc838e23d36/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e2c64ac7b3290c2cfe1effeb7a5c46ccf9c6136e/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "a4867104b545e0cffa07cc71b471773f8a9216db78009bdd1c9f1421c3a0ebaf", + "provenance_path": "tasks/86db919f95f8fdc838e23d36/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e2c64ac7b3290c2cfe1effeb7a5c46ccf9c6136e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "966b1127e3d07b4f906620046a02f46be1ffb70b", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70", + "task_sha256": "03d4ac79223320b7a23aa87a735459968b463cf1457f4ea492c5e9fd057bde56", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/provenance.json b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..32e311eee4ea3d29db3586c08553c1f79c71bce3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "01f5059a524fa9d0aa01dc811a8155e6431d3665b2044959074cbf33760493c0", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e2c64ac7b3290c2cfe1effeb7a5c46ccf9c6136e/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "9a68076b7e01ab52fe11b05d504d69daf10efce2fbd07c8b5fd051ea38a6408b", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "f95f8c4d1c87bb3a7bd085afea9c1b95116579081dab3e39902c2e311457ccf8", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "f817ef2c570f1a9099f1861cd6f858aa5a3647d3", + "instruction_sha256": "11b545421a29cd553e770b1af92727ea50261cc9da430998fc31b5031211ecaa", + "is_fork": true, + "learner_path": "tasks/86db919f95f8fdc838e23d36/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "actual_upstream_url": "https://raw.githubusercontent.com/marshmallow-code/marshmallow/9716fc629976c9d3ce30cd15d270d9ac235eb725/LICENSE", + "reviewed": true, + "sha256": "906b5d9051e426144cb173ad911667b8ebd05a9c584c2c26c135b32a3ed12001", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/marshmallow-code__marshmallow.9716fc62/e2c64ac7b3290c2cfe1effeb7a5c46ccf9c6136e/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "9716fc629976c9d3ce30cd15d270d9ac235eb725", + "patch_sha256": "a4867104b545e0cffa07cc71b471773f8a9216db78009bdd1c9f1421c3a0ebaf", + "provenance_path": "tasks/86db919f95f8fdc838e23d36/source-proof.json", + "repository_lineage": [ + "swesmith/marshmallow-code__marshmallow.9716fc62", + "marshmallow-code/marshmallow" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "e2c64ac7b3290c2cfe1effeb7a5c46ccf9c6136e", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "966b1127e3d07b4f906620046a02f46be1ffb70b", + "source_kind": "mutation", + "source_repo": "swesmith/marshmallow-code__marshmallow.9716fc62", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70", + "task_sha256": "03d4ac79223320b7a23aa87a735459968b463cf1457f4ea492c5e9fd057bde56", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "marshmallow-code/marshmallow", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "243afcb5de791cd2f1414e5f202f22f044a7b2030afe5f47f7c3449d44482b91" +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/provided-gold.diff b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..cf5aeb3f645e1f79f966d824bc27259995d2db90 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/provided-gold.diff @@ -0,0 +1,13 @@ +diff --git a/src/marshmallow/schema.py b/src/marshmallow/schema.py +index d33779fb46a5340d60478329a9002a21ebe48dfb..e21768e9461e79664359a6c2b82fb578c6cf3655 100644 +--- a/src/marshmallow/schema.py ++++ b/src/marshmallow/schema.py +@@ -478,7 +478,7 @@ + .. versionchanged:: 3.0.0a1 + Changed position of ``obj`` and ``attr``. + """ +- return get_value(attr, obj, default) ++ return get_value(obj, attr, default) + + ##### Serialization/Deserialization API ##### + diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/solution/solve.sh b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..882ad5682f3a9530af702df6f7ad53dd9c802313 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/solution/solve.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/marshmallow/schema.py b/src/marshmallow/schema.py +index d33779fb46a5340d60478329a9002a21ebe48dfb..e21768e9461e79664359a6c2b82fb578c6cf3655 100644 +--- a/src/marshmallow/schema.py ++++ b/src/marshmallow/schema.py +@@ -478,7 +478,7 @@ + .. versionchanged:: 3.0.0a1 + Changed position of ``obj`` and ``attr``. + """ +- return get_value(attr, obj, default) ++ return get_value(obj, attr, default) + + ##### Serialization/Deserialization API ##### + +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/task.toml b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9192d588b4cf4f57b589723755681d6b93b9235e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:92dc34006baf8731b08c9ac4924ee7f0990b17ee2d5ce82297208d230ebfa03f" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/check_pytest.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/expected-panels.json b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..d005f99047d582a3185784c7251d6d80e9b37a19 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/expected-panels.json @@ -0,0 +1,1180 @@ +{ + "fail-to-pass": [ + "tests/test_decorators.py::test_decorated_processors[True]", + "tests/test_decorators.py::test_decorated_processors[False]", + "tests/test_decorators.py::test_decorated_processor_returning_none[exclude]", + "tests/test_decorators.py::test_decorated_processor_returning_none[include]", + "tests/test_decorators.py::test_decorated_processor_returning_none[raise]", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_single", + "tests/test_decorators.py::TestPassOriginal::test_pass_original_many", + "tests/test_decorators.py::test_pre_dump_is_invoked_before_implicit_field_generation", + "tests/test_decorators.py::test_decorator_post_dump_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_symmetry", + "tests/test_fields.py::TestField::test_custom_field_follows_data_key_if_set", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[only-fields_list0]", + "tests/test_fields.py::TestNestedField::test_nested_schema_only_and_exclude[exclude-fields_list1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_class_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_class_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_fields.py::TestListNested::test_list_nested_instance_multiple_dumps", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[only-expected_attribute0-expected_dump0]", + "tests/test_fields.py::TestListNested::test_list_nested_lambda_only_and_exclude_merged_with_nested[exclude-expected_attribute1-expected_dump1]", + "tests/test_options.py::TestUnordered::test_unordered_dump_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[False]", + "tests/test_options.py::TestFieldOrdering::test_ordered_option_is_inherited[True]", + "tests/test_options.py::TestFieldOrdering::test_declared_field_order_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_dump", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_exclude_arg_is_maintained", + "tests/test_options.py::TestFieldOrdering::test_meta_fields_order_is_maintained_on_dump", + "tests/test_registry.py::test_two_way_nesting", + "tests/test_registry.py::test_nesting_with_class_name_many", + "tests/test_registry.py::test_invalid_class_name_in_nested_field_raises_error", + "tests/test_registry.py::test_multiple_classes_with_same_name_raises_error", + "tests/test_registry.py::test_can_use_full_module_path_to_class", + "tests/test_schema.py::test_serializing_basic_object[UserSchema]", + "tests/test_schema.py::test_serializing_basic_object[UserMetaSchema]", + "tests/test_schema.py::test_serializer_dump", + "tests/test_schema.py::test_dump_many", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value0]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value1]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value2]", + "tests/test_schema.py::test_boolean_can_dump_unhashable[value3]", + "tests/test_schema.py::test_dump_returns_a_dict", + "tests/test_schema.py::test_dumps_returns_a_string", + "tests/test_schema.py::test_dumping_single_object_with_collection_schema", + "tests/test_schema.py::test_dumps_many", + "tests/test_schema.py::test_serializing_none", + "tests/test_schema.py::test_default_many_symmetry", + "tests/test_schema.py::test_dumps_returns_json", + "tests/test_schema.py::test_serialize_many[UserSchema]", + "tests/test_schema.py::test_serialize_many[UserMetaSchema]", + "tests/test_schema.py::test_inheriting_schema", + "tests/test_schema.py::test_email_field[UserSchema]", + "tests/test_schema.py::test_email_field[UserMetaSchema]", + "tests/test_schema.py::test_integer_field", + "tests/test_schema.py::test_as_string", + "tests/test_schema.py::test_serializing_generator[UserSchema]", + "tests/test_schema.py::test_serializing_generator[UserMetaSchema]", + "tests/test_schema.py::test_serializing_dict", + "tests/test_schema.py::test_serializing_dict_with_meta_fields", + "tests/test_schema.py::test_exclude_in_init[UserSchema]", + "tests/test_schema.py::test_exclude_in_init[UserMetaSchema]", + "tests/test_schema.py::test_only_in_init[UserSchema]", + "tests/test_schema.py::test_only_in_init[UserMetaSchema]", + "tests/test_schema.py::test_json_module_is_deprecated", + "tests/test_schema.py::test_render_module", + "tests/test_schema.py::test_nested_custom_set_in_exclude_reusing_schema", + "tests/test_schema.py::test_nested_only", + "tests/test_schema.py::test_nested_only_inheritance", + "tests/test_schema.py::test_nested_only_empty_inheritance", + "tests/test_schema.py::test_nested_exclude", + "tests/test_schema.py::test_nested_exclude_inheritance", + "tests/test_schema.py::test_nested_only_and_exclude", + "tests/test_schema.py::test_nested_only_then_exclude_inheritance", + "tests/test_schema.py::test_nested_exclude_then_only_inheritance", + "tests/test_schema.py::test_nested_exclude_and_only_inheritance", + "tests/test_schema.py::test_nested_instance_many", + "tests/test_schema.py::test_nested_instance_only", + "tests/test_schema.py::test_nested_instance_exclude", + "tests/test_schema.py::test_meta_nested_exclude", + "tests/test_schema.py::test_nested_custom_set_not_implementing_getitem", + "tests/test_schema.py::test_deeply_nested_only_and_exclude", + "tests/test_schema.py::test_nested_lambda", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_load_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_load_only", + "tests/test_schema.py::test_nested_constructor_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude", + "tests/test_schema.py::test_only_and_exclude_with_fields", + "tests/test_schema.py::test_only_and_exclude_with_additional", + "tests/test_schema.py::test_nested_with_sets", + "tests/test_schema.py::test_meta_serializer_fields", + "tests/test_schema.py::test_meta_fields_mapping", + "tests/test_schema.py::test_exclude_fields", + "tests/test_schema.py::test_datetimeformat_option", + "tests/test_schema.py::test_dateformat_option", + "tests/test_schema.py::test_timeformat_option", + "tests/test_schema.py::test_default_dateformat", + "tests/test_schema.py::test_inherit_meta", + "tests/test_schema.py::test_additional", + "tests/test_schema.py::test_serializing_none_meta", + "tests/test_schema.py::TestNestedSchema::test_nested_many_with_missing_attribute", + "tests/test_schema.py::TestNestedSchema::test_nested_with_attribute_none", + "tests/test_schema.py::TestNestedSchema::test_nested_field_does_not_validate_required", + "tests/test_schema.py::TestNestedSchema::test_nested_none", + "tests/test_schema.py::TestNestedSchema::test_nested", + "tests/test_schema.py::TestNestedSchema::test_nested_many_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_meta_many", + "tests/test_schema.py::TestNestedSchema::test_nested_only", + "tests/test_schema.py::TestNestedSchema::test_exclude", + "tests/test_schema.py::TestNestedSchema::test_list_field", + "tests/test_schema.py::TestNestedSchema::test_nested_method_field", + "tests/test_schema.py::TestNestedSchema::test_nested_function_field", + "tests/test_schema.py::TestNestedSchema::test_serializer_meta_with_nested_fields", + "tests/test_schema.py::TestNestedSchema::test_serializer_with_nested_meta_fields", + "tests/test_schema.py::TestNestedSchema::test_nested_fields_must_be_passed_a_serializer", + "tests/test_schema.py::TestPluckSchema::test_pluck[UserSchema]", + "tests/test_schema.py::TestPluckSchema::test_pluck[user_schema1]", + "tests/test_schema.py::TestPluckSchema::test_pluck_none", + "tests/test_schema.py::TestPluckSchema::test_pluck_with_data_key", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_lambda", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_by_passing_class_name", + "tests/test_schema.py::TestSelfReference::test_nesting_schema_self_string", + "tests/test_schema.py::TestSelfReference::test_nesting_within_itself_meta", + "tests/test_schema.py::TestSelfReference::test_nested_self_with_only_param", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_lambda", + "tests/test_schema.py::TestSelfReference::test_multiple_pluck_self_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_lambda", + "tests/test_schema.py::TestSelfReference::test_nested_self_many_string", + "tests/test_schema.py::TestSelfReference::test_nested_self_list", + "tests/test_schema.py::TestSelfReference::test_nested_self_list_string", + "tests/test_schema.py::test_serialization_with_required_field", + "tests/test_schema.py::TestContext::test_nested_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_field_with_unpicklable_object_in_context", + "tests/test_schema.py::test_serializer_can_specify_nested_object_as_attribute", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_dump_output", + "tests/test_schema.py::TestDefaults::test_none_is_serialized_to_none", + "tests/test_schema.py::TestDefaults::test_default_and_value_missing", + "tests/test_schema.py::TestLoadOnly::test_load_only", + "tests/test_schema.py::TestFromDict::test_meta_options_are_applied", + "tests/test_schema.py::test_set_dict_class[dict]", + "tests/test_schema.py::test_set_dict_class[OrderedDict]", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_load_only_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_param", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_data_key_as_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_with_attribute_and_data_key_uses_data_key", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_value", + "tests/test_serialization.py::TestSchemaSerialization::test_serialize_with_missing_param_callable", + "tests/test_serialization.py::test_serializing_named_tuple_with_meta", + "tests/test_serialization.py::test_serializing_slice", + "tests/test_serialization.py::test_nested_field_many_serializing_generator" + ], + "pass-to-pass": [ + "tests/test_decorators.py::test_decorated_processor_inheritance", + "tests/test_decorators.py::TestValidatesDecorator::test_validates", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_attribute", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_decorator", + "tests/test_decorators.py::TestValidatesDecorator::test_field_not_present", + "tests/test_decorators.py::TestValidatesDecorator::test_precedence", + "tests/test_decorators.py::TestValidatesDecorator::test_validates_with_data_key", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_invalid_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_schema_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_field_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[True-expected_data0-expected_original_data0-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_validator_nested_many_pass_original_and_pass_many[False-expected_data1-expected_original_data1-data0]", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_decorated_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_multiple_validators_merge_dict_errors", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_passing_original_data", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_reporting_field_errors_in_schema_validator", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_allow_arbitrary_field_names_in_error", + "tests/test_decorators.py::TestValidatesSchemaDecorator::test_skip_on_field_errors", + "tests/test_decorators.py::test_decorator_error_handling", + "tests/test_decorators.py::test_decorator_error_handling_with_load[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[pre_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_load_dict_error[post_load]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[pre_dump]", + "tests/test_decorators.py::test_decorator_error_handling_with_dump[post_dump]", + "tests/test_decorators.py::test_decorator_post_load_with_nested_original_and_pass_many[data0-expected_data0-expected_original_data0]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_allow_none_deserialize_to_none[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[String]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Integer]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Boolean]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Float]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Number]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[DateTime]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Time]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Date]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[TimeDelta]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Dict]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Url]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Email]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[UUID]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[Decimal]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IP]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPInterface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv4Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[IPv6Interface]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass20]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass21]", + "tests/test_deserialization.py::TestDeserializingNone::test_fields_dont_allow_none_by_default[FieldClass22]", + "tests/test_deserialization.py::TestDeserializingNone::test_allow_none_is_true_if_missing_is_true", + "tests/test_deserialization.py::TestDeserializingNone::test_list_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_tuple_field_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_allow_none_deserialize_none_to_none", + "tests/test_deserialization.py::TestDeserializingNone::test_list_of_nested_non_allow_none_deserialize_none_to_validation_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[bad]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[in_val2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_float_field_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_overflow", + "tests/test_deserialization.py::TestFieldDeserialization::test_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_strict_integer_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_with_places_and_rounding", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_deserialization_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_decimal_field_special_values_not_permitted", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-nan-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_float_field_allow_nan[-inf-True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_string_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[notvalid]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_truthy_values_invalid[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_empty_truthy", + "tests/test_deserialization.py::TestFieldDeserialization::test_boolean_field_deserialization_with_custom_falsy_values", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_toggle_show_invalid_value_in_error_message", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[not-a-datetime]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[True]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[False]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[in_value6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_datetime_deserialization[2018-01-01]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_date_format_datetime_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-expected0-False-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45+00:00-expected1-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123+00:00-expected2-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45.123456+00:00-expected3-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_datetime_field_deserialization[2013-11-10T01:23:45-06:00-expected4-True-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.12-expected3]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1384043025.123456-expected4]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp-1-expected5]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1384043025000-expected6]", + "tests/test_deserialization.py::TestFieldDeserialization::test_timestamp_field_deserialization[timestamp_ms-1000-expected7]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[!@#-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[-1-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timestamp_field_deserialization[in_value3-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOSError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp]", + "tests/test_deserialization.py::TestFieldDeserialization::test_oversized_timestamp_field_deserialization[MockDateTimeOverflowError-timestamp_ms]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-None-2013-11-10T01:23:45-expected0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone1-2013-11-10T01:23:45+00:00-expected1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_naive_datetime_with_timezone[iso-timezone2-2013-11-10T01:23:45-03:00-expected2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone0]", + "tests/test_deserialization.py::TestFieldDeserialization::test_aware_datetime_default_timezone[iso-2013-11-10T01:23:45-timezone1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[in_data2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_time_field_deserialization[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_custom_time_format_time_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45-expected0-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45+01:00-expected1-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123-expected2-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-iso8601]", + "tests/test_deserialization.py::TestFieldDeserialization::test_iso_time_field_deserialization[01:23:45.123456-expected3-None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_precision", + "tests/test_deserialization.py::TestFieldDeserialization::test_timedelta_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[badvalue]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_timedelta_field_deserialization[9999999999]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[None]", + "tests/test_deserialization.py::TestFieldDeserialization::test_date_field_deserialization[%Y-%m-%d]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_date_field_deserialization[21-08-2014]", + "tests/test_deserialization.py::TestFieldDeserialization::test_dict_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_structured_dict_key_value_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_relative_url_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_url_field_schemes_argument", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_email_field_non_list_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_deserialization_with_context", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_only_is_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_function_field_passed_deserialize_and_serialize_is_not_load_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_uuid_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[in_value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_uuid_deserialization[tooshort]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ip_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ip_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipinterface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipinterface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv4interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[192.168.0.1/33]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:81d::200e]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv4interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_ipv6interface_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[malformed]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[123]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[\\x01\\x02\\x03]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[ff::aa:1::2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[192.168.0.1/24]", + "tests/test_deserialization.py::TestFieldDeserialization::test_invalid_ipv6interface_deserialization[2a00:1450:4001:824::200e/129]", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_symbol_not_string", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_invalid_value", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_true_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_enum_field_by_value_field_wrong_type", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_function_must_be_callable", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialization_is_noop_by_default", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_deserialization_method_must_be_a_method", + "tests/test_deserialization.py::TestFieldDeserialization::test_method_field_deserialize_only", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_list_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_list_field_deserialize_value_that_is_not_a_list[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_datetime_int_tuple_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_item", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_multiple_invalid_items", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[notalist]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[42]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_value_that_is_not_a_collection[value2]", + "tests/test_deserialization.py::TestFieldDeserialization::test_tuple_field_deserialize_invalid_length", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_field_deserialization", + "tests/test_deserialization.py::TestFieldDeserialization::test_constant_is_always_included_in_deserialized_data", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_function", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_class_that_returns_bool", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validator_that_raises_error_with_list", + "tests/test_deserialization.py::TestFieldDeserialization::test_validator_must_return_false_to_raise_error", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_validator_with_nonascii_input", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_user_validators", + "tests/test_deserialization.py::TestFieldDeserialization::test_field_deserialization_with_custom_error_message", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_values", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_many", + "tests/test_deserialization.py::TestSchemaDeserialization::test_exclude", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_list_deserialization_to_dict", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_none_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_non_not_allowed", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_single_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_many_required_missing", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_only_basestring_with_list_data", + "tests/test_deserialization.py::TestSchemaDeserialization::test_nested_none_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_data_key_as_empty_string", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_dump_only_param", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_value", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_callable", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialize_with_missing_param_none", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_raises_with_errors_with_multiple_validators", + "tests/test_deserialization.py::TestSchemaDeserialization::test_deserialization_many_raises_errors", + "tests/test_deserialization.py::TestSchemaDeserialization::test_validation_errors_are_stored", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_an_email_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_multiple_errors_can_be_stored_for_a_url_field", + "tests/test_deserialization.py::TestSchemaDeserialization::test_required_value_only_passed_to_validators_if_provided", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[True]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_deserialization[False]", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_partial_fields_validation", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_precedence", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_data_key", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_deserialization_with_index_errors_false", + "tests/test_deserialization.py::TestSchemaDeserialization::test_dump_only_fields_considered_unknown", + "tests/test_deserialization.py::TestSchemaDeserialization::test_unknown_fields_do_not_unpack_dotted_names", + "tests/test_deserialization.py::TestValidation::test_integer_with_validator", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_integer_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_float_with_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_string_validator", + "tests/test_deserialization.py::TestValidation::test_function_validator", + "tests/test_deserialization.py::TestValidation::test_function_validators[field0]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field1]", + "tests/test_deserialization.py::TestValidation::test_function_validators[field2]", + "tests/test_deserialization.py::TestValidation::test_method_validator", + "tests/test_deserialization.py::TestValidation::test_nested_data_is_stored_when_validation_fails", + "tests/test_deserialization.py::TestValidation::test_false_value_validation", + "tests/test_deserialization.py::TestValidation::test_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_deeply_nested_partial_load", + "tests/test_deserialization.py::TestValidation::test_nested_partial_tuple", + "tests/test_deserialization.py::TestValidation::test_nested_partial_default", + "tests/test_deserialization.py::test_required_field_failure[String]", + "tests/test_deserialization.py::test_required_field_failure[Integer]", + "tests/test_deserialization.py::test_required_field_failure[Boolean]", + "tests/test_deserialization.py::test_required_field_failure[Float]", + "tests/test_deserialization.py::test_required_field_failure[Number]", + "tests/test_deserialization.py::test_required_field_failure[DateTime]", + "tests/test_deserialization.py::test_required_field_failure[Time]", + "tests/test_deserialization.py::test_required_field_failure[Date]", + "tests/test_deserialization.py::test_required_field_failure[TimeDelta]", + "tests/test_deserialization.py::test_required_field_failure[Dict]", + "tests/test_deserialization.py::test_required_field_failure[Url]", + "tests/test_deserialization.py::test_required_field_failure[Email]", + "tests/test_deserialization.py::test_required_field_failure[UUID]", + "tests/test_deserialization.py::test_required_field_failure[Decimal]", + "tests/test_deserialization.py::test_required_field_failure[IP]", + "tests/test_deserialization.py::test_required_field_failure[IPv4]", + "tests/test_deserialization.py::test_required_field_failure[IPv6]", + "tests/test_deserialization.py::test_required_field_failure[IPInterface]", + "tests/test_deserialization.py::test_required_field_failure[IPv4Interface]", + "tests/test_deserialization.py::test_required_field_failure[IPv6Interface]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass20]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass21]", + "tests/test_deserialization.py::test_required_field_failure[FieldClass22]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message1]", + "tests/test_deserialization.py::test_required_message_can_be_changed[message2]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[True-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[False-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[42-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[None-raise]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-exclude]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-include]", + "tests/test_deserialization.py::test_deserialize_raises_exception_if_input_type_is_incorrect[data4-raise]", + "tests/test_error_store.py::test_missing_is_falsy", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_none_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_none", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_string_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_custom_error_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_merging_list_and_dict_with_schema_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_string", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_custom_error", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_list", + "tests/test_error_store.py::TestMergeErrors::test_merging_dict_and_dict", + "tests/test_error_store.py::TestMergeErrors::test_deep_merging_dicts", + "tests/test_exceptions.py::TestValidationError::test_stores_message_in_list", + "tests/test_exceptions.py::TestValidationError::test_can_pass_list_of_messages", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries", + "tests/test_exceptions.py::TestValidationError::test_can_store_field_name", + "tests/test_exceptions.py::TestValidationError::test_str", + "tests/test_exceptions.py::TestValidationError::test_stores_dictionaries_in_messages_dict", + "tests/test_exceptions.py::TestValidationError::test_messages_dict_type_error_on_badval", + "tests/test_fields.py::test_field_aliases[Integer-Integer]", + "tests/test_fields.py::test_field_aliases[String-String]", + "tests/test_fields.py::test_field_aliases[Boolean-Boolean]", + "tests/test_fields.py::test_field_aliases[Url-Url]", + "tests/test_fields.py::TestField::test_repr", + "tests/test_fields.py::TestField::test_error_raised_if_uncallable_validator_passed", + "tests/test_fields.py::TestField::test_error_raised_if_missing_is_set_on_required_field", + "tests/test_fields.py::TestField::test_custom_field_receives_attr_and_obj", + "tests/test_fields.py::TestField::test_custom_field_receives_data_key_if_set", + "tests/test_fields.py::TestParentAndName::test_simple_field_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_unbound_field_root_returns_none", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_mapping_field_inner_parent_and_name", + "tests/test_fields.py::TestParentAndName::test_simple_field_root", + "tests/test_fields.py::TestParentAndName::test_list_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_tuple_field_inner_root", + "tests/test_fields.py::TestParentAndName::test_list_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_dict_root_inheritance", + "tests/test_fields.py::TestParentAndName::test_datetime_list_inner_format", + "tests/test_fields.py::TestParentAndName::test_field_named_parent_has_root", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[String]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Integer]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Boolean]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Float]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Number]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[DateTime]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Time]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Date]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Dict]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Url]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Email]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[UUID]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[Decimal]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IP]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPInterface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_extra_metadata_may_be_added_to_field[FieldClass22]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestMetadata::test_field_metadata_added_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_load_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[String]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Integer]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Boolean]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Float]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Number]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[DateTime]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Time]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Date]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[TimeDelta]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Dict]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Url]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Email]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[UUID]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[Decimal]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IP]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPInterface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv4Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[IPv6Interface]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass20]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass21]", + "tests/test_fields.py::TestDeprecatedDefaultAndMissing::test_dump_default_in_deprecated_style_warns[FieldClass22]", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages_cstm_msg", + "tests/test_fields.py::TestErrorMessages::test_default_error_messages_get_merged_with_parent_error_messages", + "tests/test_fields.py::TestErrorMessages::test_make_error_key_doesnt_exist", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[only]", + "tests/test_fields.py::TestNestedField::test_nested_only_and_exclude_as_string[exclude]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[nested_value0]", + "tests/test_fields.py::TestNestedField::test_nested_instantiation_from_dict[]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[None-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[exclude-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[include-raise]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-exclude]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-include]", + "tests/test_fields.py::TestNestedField::test_nested_unknown_override[raise-raise]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestListNested::test_list_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestListNested::test_list_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestTupleNested::test_tuple_nested_partial_propagated_to_nested", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[exclude]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[dump_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_exclude_dump_only_load_only_propagated_to_nested[load_only]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[only-expected0]", + "tests/test_fields.py::TestDictNested::test_dict_nested_only_and_exclude_merged_with_nested[exclude-expected1]", + "tests/test_fields.py::TestDictNested::test_dict_nested_partial_propagated_to_nested", + "tests/test_options.py::TestUnordered::test_unordered_load_returns_dict", + "tests/test_options.py::TestFieldOrdering::test_ordering_is_off_by_default", + "tests/test_options.py::TestFieldOrdering::test_nested_field_order_with_only_arg_is_maintained_on_load", + "tests/test_options.py::TestIncludeOption::test_fields_are_added", + "tests/test_options.py::TestIncludeOption::test_included_fields_ordered_after_declared_fields", + "tests/test_options.py::TestIncludeOption::test_added_fields_are_inherited", + "tests/test_options.py::TestManyOption::test_many_by_default", + "tests/test_options.py::TestManyOption::test_explicit_single", + "tests/test_registry.py::test_serializer_has_class_registry", + "tests/test_registry.py::test_register_class_meta_option", + "tests/test_registry.py::test_serializer_class_registry_register_same_classname_different_module", + "tests/test_registry.py::test_serializer_class_registry_override_if_same_classname_same_module", + "tests/test_registry.py::test_multiple_classes_with_all", + "tests/test_schema.py::test_load_resets_errors", + "tests/test_schema.py::test_load_validation_error_stores_input_data_and_valid_data", + "tests/test_schema.py::test_load_resets_error_fields", + "tests/test_schema.py::test_errored_fields_do_not_appear_in_output", + "tests/test_schema.py::test_load_many_stores_error_indices", + "tests/test_schema.py::test_multiple_errors_can_be_stored_for_a_given_index", + "tests/test_schema.py::test_loading_single_object_with_collection_schema", + "tests/test_schema.py::test_load_returns_an_object", + "tests/test_schema.py::test_load_many", + "tests/test_schema.py::test_load_invalid_input_type[None]", + "tests/test_schema.py::test_load_invalid_input_type[False]", + "tests/test_schema.py::test_load_invalid_input_type[1]", + "tests/test_schema.py::test_load_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_invalid_input_type[val4]", + "tests/test_schema.py::test_load_invalid_input_type[val5]", + "tests/test_schema.py::test_load_invalid_input_type[val6]", + "tests/test_schema.py::test_load_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_invalid_input_type[None]", + "tests/test_schema.py::test_load_many_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_invalid_input_type[val6]", + "tests/test_schema.py::test_load_many_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_empty_collection[val0]", + "tests/test_schema.py::test_load_many_empty_collection[val1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[False]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[1.2]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val3]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val4]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[val5]", + "tests/test_schema.py::test_load_many_in_nested_invalid_input_type[lol]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val0]", + "tests/test_schema.py::test_load_many_in_nested_empty_collection[val1]", + "tests/test_schema.py::test_loads_returns_a_user", + "tests/test_schema.py::test_loads_many", + "tests/test_schema.py::test_loads_deserializes_from_json", + "tests/test_schema.py::test_on_bind_field_hook", + "tests/test_schema.py::test_nested_on_bind_field_hook", + "tests/test_schema.py::TestValidate::test_validate_raises_with_errors_dict", + "tests/test_schema.py::TestValidate::test_validate_many", + "tests/test_schema.py::TestValidate::test_validate_many_doesnt_store_index_if_index_errors_option_is_false", + "tests/test_schema.py::TestValidate::test_validate", + "tests/test_schema.py::TestValidate::test_validate_required", + "tests/test_schema.py::test_fields_are_not_copies[UserSchema]", + "tests/test_schema.py::test_fields_are_not_copies[UserMetaSchema]", + "tests/test_schema.py::test_relative_url_field", + "tests/test_schema.py::test_stores_invalid_url_error[UserSchema]", + "tests/test_schema.py::test_stores_invalid_url_error[UserMetaSchema]", + "tests/test_schema.py::test_stored_invalid_email", + "tests/test_schema.py::test_fields_must_be_declared_as_instances", + "tests/test_schema.py::test_bind_field_does_not_swallow_typeerror", + "tests/test_schema.py::test_serializing_empty_list_returns_empty_list", + "tests/test_schema.py::test_invalid_only_param", + "tests/test_schema.py::test_custom_error_message", + "tests/test_schema.py::test_custom_unknown_error_message", + "tests/test_schema.py::test_custom_type_error_message", + "tests/test_schema.py::test_custom_type_error_message_with_many", + "tests/test_schema.py::test_custom_error_messages_with_inheritance", + "tests/test_schema.py::test_load_errors_with_many", + "tests/test_schema.py::test_error_raised_if_fields_option_is_not_list", + "tests/test_schema.py::test_error_raised_if_additional_option_is_not_list", + "tests/test_schema.py::test_data_key_collision[f1]", + "tests/test_schema.py::test_data_key_collision[f5]", + "tests/test_schema.py::test_data_key_collision[None]", + "tests/test_schema.py::test_attribute_collision[f1]", + "tests/test_schema.py::test_attribute_collision[f5]", + "tests/test_schema.py::test_attribute_collision[None]", + "tests/test_schema.py::TestDeeplyNestedLoadOnly::test_dump_only", + "tests/test_schema.py::TestDeeplyNestedListLoadOnly::test_dump_only", + "tests/test_schema.py::test_invalid_only_and_exclude_with_fields", + "tests/test_schema.py::test_invalid_only_and_exclude_with_additional", + "tests/test_schema.py::test_exclude_invalid_attribute", + "tests/test_schema.py::test_only_bounded_by_fields", + "tests/test_schema.py::test_only_bounded_by_additional", + "tests/test_schema.py::test_only_empty", + "tests/test_schema.py::test_only_and_exclude_as_string[only]", + "tests/test_schema.py::test_only_and_exclude_as_string[exclude]", + "tests/test_schema.py::test_meta_field_not_on_obj_raises_attribute_error", + "tests/test_schema.py::test_fields_option_must_be_list_or_tuple", + "tests/test_schema.py::test_exclude_option_must_be_list_or_tuple", + "tests/test_schema.py::test_inherit_meta_override", + "tests/test_schema.py::test_cant_set_both_additional_and_fields", + "tests/test_schema.py::TestFieldValidation::test_errors_are_cleared_after_loading_collection", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_list", + "tests/test_schema.py::TestFieldValidation::test_raises_error_with_dict", + "tests/test_schema.py::TestFieldValidation::test_ignored_if_not_in_only", + "tests/test_schema.py::test_schema_repr", + "tests/test_schema.py::TestNestedSchema::test_nested_load_many", + "tests/test_schema.py::TestNestedSchema::test_nested_errors", + "tests/test_schema.py::TestNestedSchema::test_invalid_type_passed_to_nested_field", + "tests/test_schema.py::TestNestedSchema::test_all_errors_on_many_nested_field_with_validates_decorator", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[None]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[raise]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[include]", + "tests/test_schema.py::TestNestedSchema::test_nested_unknown_validation[exclude]", + "tests/test_schema.py::test_deserialization_with_required_field", + "tests/test_schema.py::test_deserialization_with_required_field_and_custom_validator", + "tests/test_schema.py::TestContext::test_context_method", + "tests/test_schema.py::TestContext::test_context_method_function", + "tests/test_schema.py::TestContext::test_function_field_raises_error_when_context_not_available", + "tests/test_schema.py::TestContext::test_function_field_handles_bound_serializer", + "tests/test_schema.py::TestContext::test_fields_context", + "tests/test_schema.py::TestContext::test_nested_list_fields_inherit_context", + "tests/test_schema.py::TestContext::test_nested_dict_fields_inherit_context", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inherit_fields_from_non_schema_subclass", + "tests/test_schema.py::TestFieldInheritance::test_inheritance_follows_mro", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_is_used", + "tests/test_schema.py::TestGetAttribute::test_get_attribute_with_many", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_missing", + "tests/test_schema.py::TestRequiredFields::test_required_string_field_failure", + "tests/test_schema.py::TestRequiredFields::test_allow_none_param", + "tests/test_schema.py::TestRequiredFields::test_allow_none_custom_message", + "tests/test_schema.py::TestDefaults::test_loading_none", + "tests/test_schema.py::TestDefaults::test_missing_inputs_are_excluded_from_load_output", + "tests/test_schema.py::TestLoadOnly::test_dump_only", + "tests/test_schema.py::TestLoadOnly::test_url_field_requre_tld_false", + "tests/test_schema.py::TestFromDict::test_generates_schema", + "tests/test_schema.py::TestFromDict::test_name", + "tests/test_schema.py::TestFromDict::test_generated_schemas_are_not_registered", + "tests/test_schema.py::test_class_registry_returns_schema_type", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[meta]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[init]", + "tests/test_schema.py::test_unknown_parameter_value_is_validated[load]", + "tests/test_serialization.py::TestFieldSerialization::test_number[42-42.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[0-0.0]", + "tests/test_serialization.py::TestFieldSerialization::test_number[None-None]", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string", + "tests/test_serialization.py::TestFieldSerialization::test_number_as_string_passed_none", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_func", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_deserialize_and_serialize_is_not_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_serialize_with_context", + "tests/test_serialization.py::TestFieldSerialization::test_function_field_passed_uncallable_object", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_as_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default", + "tests/test_serialization.py::TestFieldSerialization::test_integer_field_default_set_to_none", + "tests/test_serialization.py::TestFieldSerialization::test_uuid_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_address_field", + "tests/test_serialization.py::TestFieldSerialization::test_ip_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv4_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_ipv6_interface_field", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_symbol_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_true_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_enum_field_by_value_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_string", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_special_values_not_permitted", + "tests/test_serialization.py::TestFieldSerialization::test_decimal_field_fixed_point_representation", + "tests/test_serialization.py::TestFieldSerialization::test_boolean_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_email_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_dict_field_serialize_ordereddict", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_structured_dict_key_value_serialize", + "tests/test_serialization.py::TestFieldSerialization::test_url_field_serialize_none", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_method_missing", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_serialize_only_is_dump_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_passed_deserialize_only_is_load_only", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_with_uncallable_attribute", + "tests/test_serialization.py::TestFieldSerialization::test_method_field_does_not_swallow_attribute_error", + "tests/test_serialization.py::TestFieldSerialization::test_method_with_no_serialize_is_missing", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value0-0]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value1-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value2-1384043025]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp-value3-1384064625]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value4-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value5-1384043025000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_timestamp[timestamp_ms-value6-1384064625000]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value0-2013-11-10T01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value1-2013-11-10T01:23:45.123456+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value2-2013-11-10T01:23:45+00:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_iso8601[value3-2013-11-10T01:23:45-06:00-None]", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_string_field", + "tests/test_serialization.py::TestFieldSerialization::test_string_field_default_to_empty_string", + "tests/test_serialization.py::TestFieldSerialization::test_time_field", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value0-01:23:45-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value1-01:23:45.123000-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-iso8601]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_iso8601[value2-01:23:45.123456-None]", + "tests/test_serialization.py::TestFieldSerialization::test_time_field_format", + "tests/test_serialization.py::TestFieldSerialization::test_date_field", + "tests/test_serialization.py::TestFieldSerialization::test_timedelta_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generator_single_value", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_multiple_values", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_set", + "tests/test_serialization.py::TestFieldSerialization::test_list_field_work_with_custom_class_with_iterator_protocol", + "tests/test_serialization.py::TestFieldSerialization::test_bad_list_field", + "tests/test_serialization.py::TestFieldSerialization::test_datetime_integer_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_tuple_field_serialize_none_returns_none", + "tests/test_serialization.py::TestFieldSerialization::test_bad_tuple_field", + "tests/test_serialization.py::TestFieldSerialization::test_serialize_does_not_apply_validators", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialization", + "tests/test_serialization.py::TestFieldSerialization::test_constant_is_always_included_in_serialized_data", + "tests/test_serialization.py::TestFieldSerialization::test_constant_field_serialize_when_omitted", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[String]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Integer]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Boolean]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Float]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Number]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[DateTime]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Time]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Date]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[TimeDelta]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Dict]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Url]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Email]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[UUID]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[Decimal]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IP]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPInterface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv4Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[IPv6Interface]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass20]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass21]", + "tests/test_serialization.py::TestFieldSerialization::test_all_fields_serialize_none_to_none[FieldClass22]", + "tests/test_serialization.py::test_serializing_named_tuple", + "tests/test_utils.py::test_missing_singleton_copy", + "tests/test_utils.py::test_get_value_from_object[obj0]", + "tests/test_utils.py::test_get_value_from_object[obj1]", + "tests/test_utils.py::test_get_value_from_object[obj2]", + "tests/test_utils.py::test_get_value_from_object[obj3]", + "tests/test_utils.py::test_get_value_from_namedtuple_with_default", + "tests/test_utils.py::test_get_value_for_nested_object", + "tests/test_utils.py::test_get_value_from_dict", + "tests/test_utils.py::test_get_value", + "tests/test_utils.py::test_set_value", + "tests/test_utils.py::test_is_keyed_tuple", + "tests/test_utils.py::test_is_collection", + "tests/test_utils.py::test_isoformat[value0-2013-11-10T01:23:45]", + "tests/test_utils.py::test_isoformat[value1-2013-11-10T01:23:45.123456+00:00]", + "tests/test_utils.py::test_isoformat[value2-2013-11-10T01:23:45+00:00]", + "tests/test_utils.py::test_isoformat[value3-2013-11-10T01:23:45-06:00]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-expected0]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45+00:00-expected1]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123+00:00-expected2]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45.123456+00:00-expected3]", + "tests/test_utils.py::test_from_iso_datetime[2013-11-10T01:23:45-06:00-expected4]", + "tests/test_utils.py::test_from_iso_time_with_microseconds", + "tests/test_utils.py::test_from_iso_time_without_microseconds", + "tests/test_utils.py::test_from_iso_date", + "tests/test_utils.py::test_from_timestamp[1676386740-expected0]", + "tests/test_utils.py::test_from_timestamp[1676386740.58-expected1]", + "tests/test_utils.py::test_from_timestamp_with_negative_value", + "tests/test_utils.py::test_from_timestamp_with_overflow_value", + "tests/test_utils.py::test_get_func_args", + "tests/test_utils.py::test_function_field_using_type_annotation", + "tests/test_validate.py::test_url_absolute_valid[http://example.org]", + "tests/test_validate.py::test_url_absolute_valid[https://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftp://example.org]", + "tests/test_validate.py::test_url_absolute_valid[ftps://example.org]", + "tests/test_validate.py::test_url_absolute_valid[http://example.co.jp]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/a%C2%B1b]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/~username/]", + "tests/test_validate.py::test_url_absolute_valid[http://info.example.com/?fred]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--mgbh0fb.xn--kgbechtv/]", + "tests/test_validate.py::test_url_absolute_valid[http://example.com/blue/red%3Fand+green]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com/?array%5Bkey%5D=value]", + "tests/test_validate.py::test_url_absolute_valid[http://xn--rsum-bpad.example.org/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_absolute_valid[http://123.45.67.8:8329/]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001:db8::ff00:42]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://[2001::1]:8329]", + "tests/test_validate.py::test_url_absolute_valid[http://www.example.com:8000/foo]", + "tests/test_validate.py::test_url_absolute_valid[http://user@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://user:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://:pass@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://@example.com]", + "tests/test_validate.py::test_url_absolute_valid[http://AZaz09-._~%2A!$&'()*+,;=:@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\\\]", + "tests/test_validate.py::test_url_absolute_invalid[https://example.org\\n]", + "tests/test_validate.py::test_url_absolute_invalid[ftp:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[ftps:///example.com/]", + "tests/test_validate.py::test_url_absolute_invalid[http//example.org]", + "tests/test_validate.py::test_url_absolute_invalid[http:///]", + "tests/test_validate.py::test_url_absolute_invalid[http:/example.org]", + "tests/test_validate.py::test_url_absolute_invalid[foo://example.org]", + "tests/test_validate.py::test_url_absolute_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_absolute_invalid[http://2001:db8::ff00:42:8329]", + "tests/test_validate.py::test_url_absolute_invalid[http://[192.168.1.1]:8329]", + "tests/test_validate.py::test_url_absolute_invalid[abc]", + "tests/test_validate.py::test_url_absolute_invalid[..]", + "tests/test_validate.py::test_url_absolute_invalid[/]", + "tests/test_validate.py::test_url_absolute_invalid[]", + "tests/test_validate.py::test_url_absolute_invalid[None]", + "tests/test_validate.py::test_url_absolute_invalid[http://user@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@pass@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://@@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://^@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%0G@example.com]", + "tests/test_validate.py::test_url_absolute_invalid[http://%@example.com]", + "tests/test_validate.py::test_url_relative_valid[http://example.org]", + "tests/test_validate.py::test_url_relative_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_valid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_valid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_valid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_relative_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_invalid[...]", + "tests/test_validate.py::test_url_relative_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_invalid[]", + "tests/test_validate.py::test_url_relative_invalid[None]", + "tests/test_validate.py::test_url_relative_only_valid[/foo/bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar]", + "tests/test_validate.py::test_url_relative_only_valid[?bar]", + "tests/test_validate.py::test_url_relative_only_valid[/foo?bar#baz]", + "tests/test_validate.py::test_url_relative_only_invalid[http//example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org\\n]", + "tests/test_validate.py::test_url_relative_only_invalid[suppliers.html]", + "tests/test_validate.py::test_url_relative_only_invalid[../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[../.../g]", + "tests/test_validate.py::test_url_relative_only_invalid[...]", + "tests/test_validate.py::test_url_relative_only_invalid[\\\\]", + "tests/test_validate.py::test_url_relative_only_invalid[]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.org]", + "tests/test_validate.py::test_url_relative_only_invalid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/foo/bar/../baz]", + "tests/test_validate.py::test_url_relative_only_invalid[https://example.com/../icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/./icons/logo.gif]", + "tests/test_validate.py::test_url_relative_only_invalid[ftp://example.com/../../../../g]", + "tests/test_validate.py::test_url_relative_only_invalid[http://example.com/g?y/./x]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.org]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://123.45.67.8/]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example.]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example:80]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://user.name:pass.word@example]", + "tests/test_validate.py::test_url_dont_require_tld_valid[http://example/foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http//example]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://example\\n]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http://.example.org]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[http:///foo/bar]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[]", + "tests/test_validate.py::test_url_dont_require_tld_invalid[None]", + "tests/test_validate.py::test_url_custom_scheme", + "tests/test_validate.py::test_url_relative_and_custom_schemes", + "tests/test_validate.py::test_url_custom_message", + "tests/test_validate.py::test_url_repr", + "tests/test_validate.py::test_url_rejects_invalid_relative_usage", + "tests/test_validate.py::test_email_valid[niceandsimple@example.com]", + "tests/test_validate.py::test_email_valid[NiCeAnDsImPlE@eXaMpLe.CoM]", + "tests/test_validate.py::test_email_valid[very.common@example.com]", + "tests/test_validate.py::test_email_valid[a.little.lengthy.but.fine@a.iana-servers.net]", + "tests/test_validate.py::test_email_valid[disposable.style.email.with+symbol@example.com]", + "tests/test_validate.py::test_email_valid[\"very.unusual.@.unusual.com\"@example.com]", + "tests/test_validate.py::test_email_valid[!#$%&'*+-/=?^_`{}|~@example.org]", + "tests/test_validate.py::test_email_valid[niceandsimple@[64.233.160.0]]", + "tests/test_validate.py::test_email_valid[niceandsimple@localhost]", + "tests/test_validate.py::test_email_valid[jos\\xe9@blah.com]", + "tests/test_validate.py::test_email_valid[\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae]", + "tests/test_validate.py::test_email_invalid[niceandsimple\\n@example.com]", + "tests/test_validate.py::test_email_invalid[NiCeAnDsImPlE@eXaMpLe.CoM\\n]", + "tests/test_validate.py::test_email_invalid[a\"b(c)d,e:f;gi[j\\\\k]l@example.com]", + "tests/test_validate.py::test_email_invalid[just\"not\"right@example.com]", + "tests/test_validate.py::test_email_invalid[user@example]", + "tests/test_validate.py::test_email_invalid[@nouser.com]", + "tests/test_validate.py::test_email_invalid[example.com]", + "tests/test_validate.py::test_email_invalid[user]", + "tests/test_validate.py::test_email_invalid[]", + "tests/test_validate.py::test_email_invalid[None]", + "tests/test_validate.py::test_email_custom_message", + "tests/test_validate.py::test_email_repr", + "tests/test_validate.py::test_range_min", + "tests/test_validate.py::test_range_max", + "tests/test_validate.py::test_range_custom_message", + "tests/test_validate.py::test_range_repr", + "tests/test_validate.py::test_length_min", + "tests/test_validate.py::test_length_max", + "tests/test_validate.py::test_length_equal", + "tests/test_validate.py::test_length_custom_message", + "tests/test_validate.py::test_length_repr", + "tests/test_validate.py::test_equal", + "tests/test_validate.py::test_equal_custom_message", + "tests/test_validate.py::test_equal_repr", + "tests/test_validate.py::test_regexp_str", + "tests/test_validate.py::test_regexp_compile", + "tests/test_validate.py::test_regexp_custom_message", + "tests/test_validate.py::test_regexp_repr", + "tests/test_validate.py::test_predicate", + "tests/test_validate.py::test_predicate_custom_message", + "tests/test_validate.py::test_predicate_repr", + "tests/test_validate.py::test_noneof", + "tests/test_validate.py::test_noneof_custom_message", + "tests/test_validate.py::test_noneof_repr", + "tests/test_validate.py::test_oneof", + "tests/test_validate.py::test_oneof_options", + "tests/test_validate.py::test_oneof_text", + "tests/test_validate.py::test_oneof_custom_message", + "tests/test_validate.py::test_oneof_repr", + "tests/test_validate.py::test_containsonly_in_list", + "tests/test_validate.py::test_contains_only_unhashable_types", + "tests/test_validate.py::test_containsonly_in_tuple", + "tests/test_validate.py::test_contains_only_in_string", + "tests/test_validate.py::test_containsonly_custom_message", + "tests/test_validate.py::test_containsonly_repr", + "tests/test_validate.py::test_containsnoneof_error_message", + "tests/test_validate.py::test_containsnoneof_in_list", + "tests/test_validate.py::test_containsnoneof_unhashable_types", + "tests/test_validate.py::test_containsnoneof_in_tuple", + "tests/test_validate.py::test_containsnoneof_in_string", + "tests/test_validate.py::test_containsnoneof_custom_message", + "tests/test_validate.py::test_containsnoneof_mixing_types", + "tests/test_validate.py::test_and", + "tests/test_version_attributes.py::test_version_attributes_deprecated" + ] +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/grade.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/panel-config.json b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..4bf890f0f751992d624ac06850df63d8766c0b4d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[tests]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd", + "tox.ini": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/test.sh b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted-inventory.json b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..51602b77e6ffdbf167400a566c00de9bb6e574e6 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted-inventory.json @@ -0,0 +1,102 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2514, + "mode": 420, + "sha256": "4045b42c920dc27cbad93c32b2369d839181b4b77214f0f851d81693514927bd" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/base.py": { + "bytes": 8963, + "mode": 420, + "sha256": "b0ae3b41d3ccf3798641e0519d8cc54b56b395d17e54afcf39a02cc16428e6b3" + }, + "tests/conftest.py": { + "bytes": 566, + "mode": 420, + "sha256": "8a6e204dade8798c79bd6f51b5343c7f439316afe7a9e5225265ddec4d185057" + }, + "tests/foo_serializer.py": { + "bytes": 97, + "mode": 420, + "sha256": "0840f9269e077404f7961dcf6f716676a3b6bc689e63594608c08290fb141c91" + }, + "tests/mypy_test_cases/test_validation_error.py": { + "bytes": 579, + "mode": 420, + "sha256": "cd31a99988128d838f9eb2d596c925d041877cd0b11d2665c678e24754b6e4ab" + }, + "tests/test_decorators.py": { + "bytes": 30937, + "mode": 420, + "sha256": "41b8036cf50c2a33759beb39fea221afa997dee3c379b7a384be05768fbb1bb5" + }, + "tests/test_deserialization.py": { + "bytes": 88128, + "mode": 420, + "sha256": "c35268007c05bf376af5d53b30ceb545bfcbf2fd00594d7dfb92fbbf44873ec2" + }, + "tests/test_error_store.py": { + "bytes": 5137, + "mode": 420, + "sha256": "125ff6ce43dd61f97fc39341de390fde8b845204e561abb9bfa1a14bf3182f8f" + }, + "tests/test_exceptions.py": { + "bytes": 1416, + "mode": 420, + "sha256": "bf954d10a9e9f04b0ee3fcfff18489853fa8f3ccf3f88cc84f35d96655609b77" + }, + "tests/test_fields.py": { + "bytes": 24578, + "mode": 420, + "sha256": "96f280b8d7ccbc5650c2e3a0b20173410b6bffafe716b236b24568365ad082cf" + }, + "tests/test_options.py": { + "bytes": 7852, + "mode": 420, + "sha256": "32e9790fda3daabc64e255b5ca81b43493a55200c781fc966ea8d483a5bb27de" + }, + "tests/test_registry.py": { + "bytes": 6907, + "mode": 420, + "sha256": "9a492812de8af2a55587d4cc6ecb0999c692e5d402a351f5afb4ce61223d507e" + }, + "tests/test_schema.py": { + "bytes": 92822, + "mode": 420, + "sha256": "67efc0bccd973043fedd6877eead645bec809c3ca00ee03c1898b9afc11e7d1f" + }, + "tests/test_serialization.py": { + "bytes": 39066, + "mode": 420, + "sha256": "cbb04513548f1ba827c55bbc2f71c4b197c913b12d6f5c3e615373b63abad95f" + }, + "tests/test_utils.py": { + "bytes": 7716, + "mode": 420, + "sha256": "0b85fa3e8e7fda607d20794827104a16572b198ad43ddde3e3d968518ecfcc59" + }, + "tests/test_validate.py": { + "bytes": 32663, + "mode": 420, + "sha256": "1ec731e95400b20742e6ac0b2e0f2e4e8e389cecd54861dd354ca3020e4378cd" + }, + "tests/test_version_attributes.py": { + "bytes": 336, + "mode": 420, + "sha256": "51dc908d1550acec3e3332ce85927fb2af4d4e684fc273c2348d6ef0a9a9f345" + }, + "tox.ini": { + "bytes": 827, + "mode": 420, + "sha256": "0d99297b2998a7fa3090bc8142f556aab6902d04a8053953ce11938253193877" + } + } +} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/pyproject.toml b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d199ea385523c2f3346324bb28a877c73b40b97e --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/pyproject.toml @@ -0,0 +1,93 @@ +[project] +name = "marshmallow" +version = "3.23.1" +description = "A lightweight library for converting complex datatypes to and from native Python datatypes." +readme = "README.rst" +license = { file = "LICENSE" } +authors = [{ name = "Steven Loria", email = "sloria1@gmail.com" }] +maintainers = [ + { name = "Steven Loria", email = "sloria1@gmail.com" }, + { name = "Jérôme Lafréchoux", email = "jerome@jolimont.fr" }, + { name = "Jared Deckard", email = "jared@shademaps.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +dependencies = ["packaging>=17.0"] + +[project.urls] +Changelog = "https://marshmallow.readthedocs.io/en/latest/changelog.html" +Funding = "https://opencollective.com/marshmallow" +Issues = "https://github.com/marshmallow-code/marshmallow/issues" +Source = "https://github.com/marshmallow-code/marshmallow" +Tidelift = "https://tidelift.com/subscription/pkg/pypi-marshmallow?utm_source=pypi-marshmallow&utm_medium=pypi" + +[project.optional-dependencies] +docs = [ + "sphinx==8.1.3", + "sphinx-issues==5.0.0", + "alabaster==1.0.0", + "sphinx-version-warning==1.1.2", + "autodocsumm==0.2.14", +] +tests = ["pytest", "simplejson"] +dev = ["marshmallow[tests]", "tox", "pre-commit>=3.5,<5.0"] + +[build-system] +requires = ["flit_core<4"] +build-backend = "flit_core.buildapi" + +[tool.flit.sdist] +include = [ + "docs/", + "tests/", + "CHANGELOG.rst", + "CONTRIBUTING.rst", + "SECURITY.md", + "NOTICE", + "tox.ini", +] +exclude = ["docs/_build/"] + +[tool.ruff] +src = ["src"] +fix = true +show-fixes = true +output-format = "full" + +[tool.ruff.format] +docstring-code-format = true + +[tool.ruff.lint] +ignore = ["E203", "E266", "E501", "E731"] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle error + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warning +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["E721"] + +[tool.mypy] +ignore_missing_imports = true +warn_unreachable = true +warn_unused_ignores = true +warn_redundant_casts = true +no_implicit_optional = true + +[tool.pytest.ini_options] +norecursedirs = ".git .ropeproject .tox docs env venv tests/mypy_test_cases" +addopts = "-v --tb=short" diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/__init__.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/base.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae1bed0bb14c79d811dd7d01dc179eab2e0b719d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/base.py @@ -0,0 +1,354 @@ +"""Test utilities and fixtures.""" + +import datetime as dt +import functools +import uuid +from enum import Enum, IntEnum +from zoneinfo import ZoneInfo + +import simplejson + +from marshmallow import Schema, fields, missing, post_load, validate +from marshmallow.exceptions import ValidationError + +central = ZoneInfo("America/Chicago") + + +class GenderEnum(IntEnum): + male = 1 + female = 2 + non_binary = 3 + + +class HairColorEnum(Enum): + black = "black hair" + brown = "brown hair" + blond = "blond hair" + red = "red hair" + + +class DateEnum(Enum): + date_1 = dt.date(2004, 2, 29) + date_2 = dt.date(2008, 2, 29) + date_3 = dt.date(2012, 2, 29) + + +ALL_FIELDS = [ + fields.String, + fields.Integer, + fields.Boolean, + fields.Float, + fields.Number, + fields.DateTime, + fields.Time, + fields.Date, + fields.TimeDelta, + fields.Dict, + fields.Url, + fields.Email, + fields.UUID, + fields.Decimal, + fields.IP, + fields.IPv4, + fields.IPv6, + fields.IPInterface, + fields.IPv4Interface, + fields.IPv6Interface, + functools.partial(fields.Enum, GenderEnum), + functools.partial(fields.Enum, HairColorEnum, by_value=fields.String), + functools.partial(fields.Enum, GenderEnum, by_value=fields.Integer), +] + + +##### Custom asserts ##### + + +def assert_date_equal(d1, d2): + assert d1.year == d2.year + assert d1.month == d2.month + assert d1.day == d2.day + + +def assert_time_equal(t1, t2): + assert t1.hour == t2.hour + assert t1.minute == t2.minute + assert t1.second == t2.second + assert t1.microsecond == t2.microsecond + + +##### Models ##### + + +class User: + SPECIES = "Homo sapiens" + + def __init__( + self, + name, + age=0, + id_=None, + homepage=None, + email=None, + registered=True, + time_registered=None, + birthdate=None, + birthtime=None, + balance=100, + sex=GenderEnum.male, + hair_color=HairColorEnum.black, + employer=None, + various_data=None, + ): + self.name = name + self.age = age + # A naive datetime + self.created = dt.datetime(2013, 11, 10, 14, 20, 58) + # A TZ-aware datetime + self.updated = dt.datetime(2013, 11, 10, 14, 20, 58, tzinfo=central) + self.id = id_ + self.homepage = homepage + self.email = email + self.balance = balance + self.registered = registered + self.hair_colors = list(HairColorEnum.__members__) + self.sex_choices = list(GenderEnum.__members__) + self.finger_count = 10 + self.uid = uuid.uuid1() + self.time_registered = time_registered or dt.time(1, 23, 45, 6789) + self.birthdate = birthdate or dt.date(2013, 1, 23) + self.birthtime = birthtime or dt.time(0, 1, 2, 3333) + self.activation_date = dt.date(2013, 12, 11) + self.sex = sex + self.hair_color = hair_color + self.employer = employer + self.relatives = [] + self.various_data = various_data or { + "pets": ["cat", "dog"], + "address": "1600 Pennsylvania Ave\n" "Washington, DC 20006", + } + + @property + def since_created(self): + return dt.datetime(2013, 11, 24) - self.created + + def __repr__(self): + return f"" + + +class Blog: + def __init__(self, title, user, collaborators=None, categories=None, id_=None): + self.title = title + self.user = user + self.collaborators = collaborators or [] # List/tuple of users + self.categories = categories + self.id = id_ + + def __contains__(self, item): + return item.name in [each.name for each in self.collaborators] + + +class DummyModel: + def __init__(self, foo): + self.foo = foo + + def __eq__(self, other): + return self.foo == other.foo + + def __str__(self): + return f"bar {self.foo}" + + +###### Schemas ##### + + +class Uppercased(fields.Field): + """Custom field formatting example.""" + + def _serialize(self, value, attr, obj): + if value: + return value.upper() + + +def get_lowername(obj): + if obj is None: + return missing + if isinstance(obj, dict): + return obj.get("name").lower() + else: + return obj.name.lower() + + +class UserSchema(Schema): + name = fields.String() + age = fields.Float() # type: fields.Field + created = fields.DateTime() + created_formatted = fields.DateTime( + format="%Y-%m-%d", attribute="created", dump_only=True + ) + created_iso = fields.DateTime(format="iso", attribute="created", dump_only=True) + updated = fields.DateTime() + species = fields.String(attribute="SPECIES") + id = fields.String(dump_default="no-id") + uppername = Uppercased(attribute="name", dump_only=True) + homepage = fields.Url() + email = fields.Email() + balance = fields.Decimal() + is_old = fields.Method("get_is_old") # type: fields.Field + lowername = fields.Function(get_lowername) + registered = fields.Boolean() + hair_colors = fields.List(fields.Raw) + sex_choices = fields.List(fields.Raw) + finger_count = fields.Integer() + uid = fields.UUID() + time_registered = fields.Time() + birthdate = fields.Date() + birthtime = fields.Time() + activation_date = fields.Date() + since_created = fields.TimeDelta() + sex = fields.Str(validate=validate.OneOf(list(GenderEnum.__members__))) + various_data = fields.Dict() + + class Meta: + render_module = simplejson + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + @post_load + def make_user(self, data, **kwargs): + return User(**data) + + +class UserMetaSchema(Schema): + """The equivalent of the UserSchema, using the ``fields`` option.""" + + uppername = Uppercased(attribute="name", dump_only=True) + balance = fields.Decimal() + is_old = fields.Method("get_is_old") + lowername = fields.Function(get_lowername) + species = fields.String(attribute="SPECIES") + homepage = fields.Url() + email = fields.Email() + various_data = fields.Dict() + + def get_is_old(self, obj): + if obj is None: + return missing + if isinstance(obj, dict): + age = obj.get("age") + else: + age = obj.age + try: + return age > 80 + except TypeError as te: + raise ValidationError(str(te)) from te + + class Meta: + fields = ( + "name", + "age", + "created", + "updated", + "id", + "homepage", + "uppername", + "email", + "balance", + "is_old", + "lowername", + "species", + "registered", + "hair_colors", + "sex_choices", + "finger_count", + "uid", + "time_registered", + "birthdate", + "birthtime", + "since_created", + "various_data", + ) + + +class UserExcludeSchema(UserSchema): + class Meta: + exclude = ("created", "updated") + + +class UserAdditionalSchema(Schema): + lowername = fields.Function(lambda obj: obj.name.lower()) + + class Meta: + additional = ("name", "age", "created", "email") + + +class UserIntSchema(UserSchema): + age = fields.Integer() + + +class UserFloatStringSchema(UserSchema): + age = fields.Float(as_string=True) + + +class ExtendedUserSchema(UserSchema): + is_old = fields.Boolean() + + +class UserRelativeUrlSchema(UserSchema): + homepage = fields.Url(relative=True) + + +class BlogSchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + categories = fields.List(fields.String) + id = fields.String() + + +class BlogUserMetaSchema(Schema): + user = fields.Nested(UserMetaSchema()) + collaborators = fields.List(fields.Nested(UserMetaSchema())) + + +class BlogSchemaMeta(Schema): + """Same as BlogSerializer but using ``fields`` options.""" + + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema())) + + class Meta: + fields = ("title", "user", "collaborators", "categories", "id") + + +class BlogOnlySchema(Schema): + title = fields.String() + user = fields.Nested(UserSchema) + collaborators = fields.List(fields.Nested(UserSchema(only=("id",)))) + + +class BlogSchemaExclude(BlogSchema): + user = fields.Nested(UserSchema, exclude=("uppername", "species")) + + +class BlogSchemaOnlyExclude(BlogSchema): + user = fields.Nested(UserSchema, only=("name",), exclude=("name", "species")) + + +class mockjson: # noqa + @staticmethod + def dumps(val): + return b"{'foo': 42}" + + @staticmethod + def loads(val): + return {"foo": 42} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/conftest.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..fec4c5cc4de97a3f71d1dbdbdae7ef902a9cff9c --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +"""Pytest fixtures that are available in all test modules.""" + +import pytest + +from tests.base import Blog, User, UserSchema + + +@pytest.fixture +def user(): + return User(name="Monty", age=42.3, homepage="http://monty.python.org/") + + +@pytest.fixture +def blog(user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + return Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + + +@pytest.fixture +def serialized_user(user): + return UserSchema().dump(user) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/foo_serializer.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/foo_serializer.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0075b74aff9aca837de50c2d1abc98793450bc --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/foo_serializer.py @@ -0,0 +1,5 @@ +from marshmallow import Schema, fields + + +class FooSerializer(Schema): + _id = fields.Integer() diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/mypy_test_cases/test_validation_error.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/mypy_test_cases/test_validation_error.py new file mode 100644 index 0000000000000000000000000000000000000000..105c7651b723fdd20e19b4249b3bcd71dfdcbf52 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/mypy_test_cases/test_validation_error.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import marshmallow as ma + +# OK types for 'message' +ma.ValidationError("foo") +ma.ValidationError(["foo"]) +ma.ValidationError({"foo": "bar"}) + +# non-OK types for 'message' +ma.ValidationError(0) # type: ignore[arg-type] + +# 'messages' is a dict|list +err = ma.ValidationError("foo") +a: dict | list = err.messages +# union type can't assign to non-union type +b: str = err.messages # type: ignore[assignment] +c: dict = err.messages # type: ignore[assignment] +# 'messages_dict' is a dict, so that it can assign to a dict +d: dict = err.messages_dict diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_decorators.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..a59fb08a1e37b558d1d280857027a58da06e9705 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_decorators.py @@ -0,0 +1,896 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + post_dump, + post_load, + pre_dump, + pre_load, + validates, + validates_schema, +) + + +@pytest.mark.parametrize("partial_val", (True, False)) +def test_decorated_processors(partial_val): + class ExampleSchema(Schema): + """Includes different ways to invoke decorators and set up methods""" + + TAG = "TAG" + + value = fields.Integer(as_string=True) + + # Implicit default raw, pre dump, static method. + @pre_dump + def increment_value(self, item, **kwargs): + assert "many" in kwargs + item["value"] += 1 + return item + + # Implicit default raw, post dump, class method. + @post_dump + def add_tag(self, item, **kwargs): + assert "many" in kwargs + item["value"] = self.TAG + item["value"] + return item + + # Explicitly raw, post dump, instance method. + @post_dump(pass_many=True) + def add_envelope(self, data, many, **kwargs): + key = self.get_envelope_key(many) + return {key: data} + + # Explicitly raw, pre load, instance method. + @pre_load(pass_many=True) + def remove_envelope(self, data, many, partial, **kwargs): + assert partial is partial_val + key = self.get_envelope_key(many) + return data[key] + + @staticmethod + def get_envelope_key(many): + return "data" if many else "datum" + + # Explicitly not raw, pre load, instance method. + @pre_load(pass_many=False) + def remove_tag(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] = item["value"][len(self.TAG) :] + return item + + # Explicit default raw, post load, instance method. + @post_load() + def decrement_value(self, item, partial, **kwargs): + assert partial is partial_val + assert "many" in kwargs + item["value"] -= 1 + return item + + schema = ExampleSchema(partial=partial_val) + + # Need to re-create these because the processors will modify in place. + make_item = lambda: {"value": 3} + make_items = lambda: [make_item(), {"value": 5}] + + item_dumped = schema.dump(make_item()) + assert item_dumped == {"datum": {"value": "TAG4"}} + item_loaded = schema.load(item_dumped) + assert item_loaded == make_item() + + items_dumped = schema.dump(make_items(), many=True) + assert items_dumped == {"data": [{"value": "TAG4"}, {"value": "TAG6"}]} + items_loaded = schema.load(items_dumped, many=True) + assert items_loaded == make_items() + + +#  Regression test for https://github.com/marshmallow-code/marshmallow/issues/347 +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +def test_decorated_processor_returning_none(unknown): + class PostSchema(Schema): + value = fields.Integer() + + @post_load + def load_none(self, item, **kwargs): + return None + + @post_dump + def dump_none(self, item, **kwargs): + return None + + class PreSchema(Schema): + value = fields.Integer() + + @pre_load + def load_none(self, item, **kwargs): + return None + + @pre_dump + def dump_none(self, item, **kwargs): + return None + + schema = PostSchema(unknown=unknown) + assert schema.dump({"value": 3}) is None + assert schema.load({"value": 3}) is None + schema = PreSchema(unknown=unknown) + assert schema.dump({"value": 3}) == {} + with pytest.raises(ValidationError) as excinfo: + schema.load({"value": 3}) + assert excinfo.value.messages == {"_schema": ["Invalid input type."]} + + +class TestPassOriginal: + def test_pass_original_single(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_original=True) + def post_load(self, data, original_data, **kwargs): + ret = data.copy() + ret["_post_load"] = original_data["sentinel"] + return ret + + @post_dump(pass_original=True) + def post_dump(self, data, obj, **kwargs): + ret = data.copy() + ret["_post_dump"] = obj["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum) + assert item_loaded["foo"] == 42 + assert item_loaded["_post_load"] == 24 + + item_dumped = schema.dump(datum) + + assert item_dumped["foo"] == 42 + assert item_dumped["_post_dump"] == 24 + + def test_pass_original_many(self): + class MySchema(Schema): + foo = fields.Field() + + @post_load(pass_many=True, pass_original=True) + def post_load(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_load"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_load"] = original["sentinel"] + return ret + + @post_dump(pass_many=True, pass_original=True) + def post_dump(self, data, original, many, **kwargs): + if many: + ret = [] + for item, orig_item in zip(data, original): + item["_post_dump"] = orig_item["sentinel"] + ret.append(item) + else: + ret = data.copy() + ret["_post_dump"] = original["sentinel"] + return ret + + schema = MySchema(unknown=EXCLUDE) + data = [{"foo": 42, "sentinel": 24}, {"foo": 424, "sentinel": 242}] + items_loaded = schema.load(data, many=True) + assert items_loaded == [ + {"foo": 42, "_post_load": 24}, + {"foo": 424, "_post_load": 242}, + ] + test_values = [e["_post_load"] for e in items_loaded] + assert test_values == [24, 242] + + items_dumped = schema.dump(data, many=True) + assert items_dumped == [ + {"foo": 42, "_post_dump": 24}, + {"foo": 424, "_post_dump": 242}, + ] + + # Also check load/dump of single item + + datum = {"foo": 42, "sentinel": 24} + item_loaded = schema.load(datum, many=False) + assert item_loaded == {"foo": 42, "_post_load": 24} + + item_dumped = schema.dump(datum, many=False) + assert item_dumped == {"foo": 42, "_post_dump": 24} + + +def test_decorated_processor_inheritance(): + class ParentSchema(Schema): + @post_dump + def inherited(self, item, **kwargs): + item["inherited"] = "inherited" + return item + + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "base" + return item + + @post_dump + def deleted(self, item, **kwargs): + item["deleted"] = "retained" + return item + + class ChildSchema(ParentSchema): + @post_dump + def overridden(self, item, **kwargs): + item["overridden"] = "overridden" + return item + + deleted = None + + parent_dumped = ParentSchema().dump({}) + assert parent_dumped == { + "inherited": "inherited", + "overridden": "base", + "deleted": "retained", + } + + child_dumped = ChildSchema().dump({}) + assert child_dumped == {"inherited": "inherited", "overridden": "overridden"} + + +# https://github.com/marshmallow-code/marshmallow/issues/229#issuecomment-138949436 +def test_pre_dump_is_invoked_before_implicit_field_generation(): + class Foo(Schema): + field = fields.Integer() + + @pre_dump + def hook(self, data, **kwargs): + data["generated_field"] = 7 + return data + + class Meta: + # Removing generated_field from here drops it from the output + fields = ("field", "generated_field") + + assert Foo().dump({"field": 5}) == {"field": 5, "generated_field": 7} + + +class ValidatesSchema(Schema): + foo = fields.Int() + + @validates("foo") + def validate_foo(self, value): + if value != 42: + raise ValidationError("The answer to life the universe and everything.") + + +class TestValidatesDecorator: + def test_validates(self): + class VSchema(Schema): + s = fields.String() + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + VSchema().load({"s": "bar"}) + + assert excinfo.value.messages == {"s": ["nope"]} + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/350 + def test_validates_with_attribute(self): + class S1(Schema): + s = fields.String(attribute="string_name") + + @validates("s") + def validate_string(self, data): + raise ValidationError("nope") + + with pytest.raises(ValidationError) as excinfo: + S1().load({"s": "foo"}) + assert excinfo.value.messages == {"s": ["nope"]} + + with pytest.raises(ValidationError): + S1(many=True).load([{"s": "foo"}]) + + def test_validates_decorator(self): + schema = ValidatesSchema() + + errors = schema.validate({"foo": 41}) + assert "foo" in errors + assert errors["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate({"foo": 42}) + assert errors == {} + + errors = schema.validate([{"foo": 42}, {"foo": 43}], many=True) + assert "foo" in errors[1] + assert len(errors[1]["foo"]) == 1 + assert errors[1]["foo"][0] == "The answer to life the universe and everything." + + errors = schema.validate([{"foo": 42}, {"foo": 42}], many=True) + assert errors == {} + + errors = schema.validate({}) + assert errors == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 41}) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert errors + assert result == {} + + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": 42}, {"foo": 43}], many=True) + errors = excinfo.value.messages + result = excinfo.value.valid_data + assert len(result) == 2 + assert result[0] == {"foo": 42} + assert result[1] == {} + assert 1 in errors + assert "foo" in errors[1] + assert errors[1]["foo"] == ["The answer to life the universe and everything."] + + def test_field_not_present(self): + class BadSchema(ValidatesSchema): + @validates("bar") + def validate_bar(self, value): + raise ValidationError("Never raised.") + + schema = BadSchema() + + with pytest.raises(ValueError, match='"bar" field does not exist.'): + schema.validate({"foo": 42}) + + def test_precedence(self): + class Schema2(ValidatesSchema): + foo = fields.Int(validate=lambda n: n != 42) + bar = fields.Int(validate=lambda n: n == 1) + + @validates("bar") + def validate_bar(self, value): + if value != 2: + raise ValidationError("Must be 2") + + schema = Schema2() + + errors = schema.validate({"foo": 42}) + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert "Invalid value." in errors["foo"][0] + + errors = schema.validate({"bar": 3}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert "Invalid value." in errors["bar"][0] + + errors = schema.validate({"bar": 1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "Must be 2" + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/748 + def test_validates_with_data_key(self): + class BadSchema(Schema): + foo = fields.String(data_key="foo-name") + + @validates("foo") + def validate_string(self, data): + raise ValidationError("nope") + + schema = BadSchema() + errors = schema.validate({"foo-name": "data"}) + assert "foo-name" in errors + assert errors["foo-name"] == ["nope"] + + schema = BadSchema() + errors = schema.validate( + [{"foo-name": "data"}, {"foo-name": "data2"}], many=True + ) + assert errors == {0: {"foo-name": ["nope"]}, 1: {"foo-name": ["nope"]}} + + +class TestValidatesSchemaDecorator: + def test_validator_nested_many_invalid_data(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [1]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["Invalid input type."]} + + def test_validator_nested_many_schema_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"_schema": ["This will never work."]} + + def test_validator_nested_many_field_error(self): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema + def validate_schema(self, data, **kwargs): + raise ValidationError("This will never work.", "foo") + + class MySchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = MySchema() + errors = schema.validate({"nested": [{"foo": 1}]}) + assert errors + assert "nested" in errors + assert 0 in errors["nested"] + assert errors["nested"][0] == {"foo": ["This will never work."]} + + @pytest.mark.parametrize("data", ([{"foo": 1, "bar": 2}],)) + @pytest.mark.parametrize( + "pass_many,expected_data,expected_original_data", + ( + [True, [{"foo": 1}], [{"foo": 1, "bar": 2}]], + [False, {"foo": 1}, {"foo": 1, "bar": 2}], + ), + ) + def test_validator_nested_many_pass_original_and_pass_many( + self, pass_many, data, expected_data, expected_original_data + ): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @validates_schema(pass_many=pass_many, pass_original=True) + def validate_schema(self, data, original_data, many, **kwargs): + assert data == expected_data + assert original_data == expected_original_data + assert many is True + raise ValidationError("Method called") + + class MySchema(Schema): + nested = fields.Nested( + NestedSchema, required=True, many=True, unknown=EXCLUDE + ) + + schema = MySchema() + errors = schema.validate({"nested": data}) + error = errors["nested"] if pass_many else errors["nested"][0] + assert error["_schema"][0] == "Method called" + + def test_decorated_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema(pass_many=True) + def validate_raw(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative", "bar") + + schema = MySchema() + errors = schema.validate({"foo": 3}) + assert "_schema" in errors + assert errors["_schema"][0] == "Must be greater than 3" + + errors = schema.validate([{"foo": 4}], many=True) + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "Must provide at least 2 items" + + errors = schema.validate({"foo": 4, "bar": -1}) + assert "bar" in errors + assert len(errors["bar"]) == 1 + assert errors["bar"][0] == "bar must not be negative" + + def test_multiple_validators(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema + def validate_schema(self, data, **kwargs): + if data["foo"] <= 3: + raise ValidationError("Must be greater than 3") + + @validates_schema + def validate_bar(self, data, **kwargs): + if "bar" in data and data["bar"] < 0: + raise ValidationError("bar must not be negative") + + schema = MySchema() + errors = schema.validate({"foo": 3, "bar": -1}) + assert type(errors) is dict + assert "_schema" in errors + assert len(errors["_schema"]) == 2 + assert "Must be greater than 3" in errors["_schema"] + assert "bar must not be negative" in errors["_schema"] + + errors = schema.validate([{"foo": 3, "bar": -1}, {"foo": 3}], many=True) + assert type(errors) is dict + assert "_schema" in errors[0] + assert len(errors[0]["_schema"]) == 2 + assert "Must be greater than 3" in errors[0]["_schema"] + assert "bar must not be negative" in errors[0]["_schema"] + assert len(errors[1]["_schema"]) == 1 + assert "Must be greater than 3" in errors[0]["_schema"] + + def test_multiple_validators_merge_dict_errors(self): + class NestedSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + class MySchema(Schema): + nested = fields.Nested(NestedSchema) + + @validates_schema + def validate_nested_foo(self, data, **kwargs): + raise ValidationError({"nested": {"foo": ["Invalid foo"]}}) + + @validates_schema + def validate_nested_bar_1(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 1"]}}) + + @validates_schema + def validate_nested_bar_2(self, data, **kwargs): + raise ValidationError({"nested": {"bar": ["Invalid bar 2"]}}) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"nested": {"foo": 1, "bar": 2}}) + + assert excinfo.value.messages == { + "nested": { + "foo": ["Invalid foo"], + "bar": ["Invalid bar 1", "Invalid bar 2"], + } + } + + def test_passing_original_data(self): + class MySchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @validates_schema(pass_original=True) + def validate_original(self, data, original_data, partial, **kwargs): + if isinstance(original_data, dict) and isinstance( + original_data["foo"], str + ): + raise ValidationError("foo cannot be a string") + + @validates_schema(pass_many=True, pass_original=True) + def validate_original_bar(self, data, original_data, many, **kwargs): + def check(datum): + if isinstance(datum, dict) and isinstance(datum["bar"], str): + raise ValidationError("bar cannot be a string") + + if many: + for each in original_data: + check(each) + else: + check(original_data) + + schema = MySchema() + + errors = schema.validate({"foo": "4", "bar": 12}) + assert errors["_schema"] == ["foo cannot be a string"] + + errors = schema.validate({"foo": 4, "bar": "42"}) + assert errors["_schema"] == ["bar cannot be a string"] + + errors = schema.validate([{"foo": 4, "bar": "42"}], many=True) + assert errors["_schema"] == ["bar cannot be a string"] + + def test_allow_reporting_field_errors_in_schema_validator(self): + class NestedSchema(Schema): + baz = fields.Int(required=True) + + class MySchema(Schema): + foo = fields.Int(required=True) + bar = fields.Nested(NestedSchema, required=True) + bam = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def consistency_validation(self, data, **kwargs): + errors = {} + if data["bar"]["baz"] != data["foo"]: + errors["bar"] = {"baz": "Non-matching value"} + if data["bam"] > data["foo"]: + errors["bam"] = "Value should be less than foo" + if errors: + raise ValidationError(errors) + + schema = MySchema() + errors = schema.validate({"foo": 2, "bar": {"baz": 5}, "bam": 6}) + assert errors["bar"]["baz"] == "Non-matching value" + assert errors["bam"] == "Value should be less than foo" + + # https://github.com/marshmallow-code/marshmallow/issues/273 + def test_allow_arbitrary_field_names_in_error(self): + class MySchema(Schema): + @validates_schema + def validator(self, data, **kwargs): + raise ValidationError("Error message", "arbitrary_key") + + errors = MySchema().validate({}) + assert errors["arbitrary_key"] == ["Error message"] + + def test_skip_on_field_errors(self): + class MySchema(Schema): + foo = fields.Int(required=True, validate=lambda n: n == 3) + bar = fields.Int(required=True) + + @validates_schema(skip_on_field_errors=True) + def validate_schema(self, data, **kwargs): + if data["foo"] != data["bar"]: + raise ValidationError("Foo and bar must be equal.") + + @validates_schema(skip_on_field_errors=True, pass_many=True) + def validate_many(self, data, many, **kwargs): + if many: + assert type(data) is list + if len(data) < 2: + raise ValidationError("Must provide at least 2 items") + + schema = MySchema() + # check that schema errors still occur with no field errors + errors = schema.validate({"foo": 3, "bar": 4}) + assert "_schema" in errors + assert errors["_schema"][0] == "Foo and bar must be equal." + + errors = schema.validate([{"foo": 3, "bar": 3}], many=True) + assert "_schema" in errors + assert errors["_schema"][0] == "Must provide at least 2 items" + + # check that schema errors don't occur when field errors do + errors = schema.validate({"foo": 3, "bar": "not an int"}) + assert "bar" in errors + assert "_schema" not in errors + + errors = schema.validate({"foo": 2, "bar": 2}) + assert "foo" in errors + assert "_schema" not in errors + + errors = schema.validate([{"foo": 3, "bar": "not an int"}], many=True) + assert "bar" in errors[0] + assert "_schema" not in errors + + +def test_decorator_error_handling(): # noqa: C901 + class ExampleSchema(Schema): + foo = fields.Int() + bar = fields.Int() + + @pre_load() + def pre_load_error1(self, item, **kwargs): + if item["foo"] != 0: + return item + errors = {"foo": ["preloadmsg1"], "bar": ["preloadmsg2", "preloadmsg3"]} + raise ValidationError(errors) + + @pre_load() + def pre_load_error2(self, item, **kwargs): + if item["foo"] != 4: + return item + raise ValidationError("preloadmsg1", "foo") + + @pre_load() + def pre_load_error3(self, item, **kwargs): + if item["foo"] != 8: + return item + raise ValidationError("preloadmsg1") + + @post_load() + def post_load_error1(self, item, **kwargs): + if item["foo"] != 1: + return item + errors = {"foo": ["postloadmsg1"], "bar": ["postloadmsg2", "postloadmsg3"]} + raise ValidationError(errors) + + @post_load() + def post_load_error2(self, item, **kwargs): + if item["foo"] != 5: + return item + raise ValidationError("postloadmsg1", "foo") + + def make_item(foo, bar): + data = schema.load({"foo": foo, "bar": bar}) + assert data is not None + return data + + schema = ExampleSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 0, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "preloadmsg2" in errors["bar"] + assert "preloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 1, "bar": 1}) + errors = excinfo.value.messages + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + assert "bar" in errors + assert len(errors["bar"]) == 2 + assert "postloadmsg2" in errors["bar"] + assert "postloadmsg3" in errors["bar"] + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 4, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "preloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 5, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "foo" in errors + assert len(errors["foo"]) == 1 + assert errors["foo"][0] == "postloadmsg1" + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": 8, "bar": 1}) + errors = excinfo.value.messages + assert len(errors) == 1 + assert "_schema" in errors + assert len(errors["_schema"]) == 1 + assert errors["_schema"][0] == "preloadmsg1" + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"foo": "error"} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_load, post_load]) +def test_decorator_error_handling_with_load_dict_error(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}, "nested_field") + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.load({}) + assert exc.value.messages == {"nested_field": {"foo": "error"}} + schema.dump(object()) + + +@pytest.mark.parametrize("decorator", [pre_dump, post_dump]) +def test_decorator_error_handling_with_dump(decorator): + class ExampleSchema(Schema): + @decorator + def raise_value_error(self, item, **kwargs): + raise ValidationError({"foo": "error"}) + + schema = ExampleSchema() + with pytest.raises(ValidationError) as exc: + schema.dump(object()) + assert exc.value.messages == {"foo": "error"} + schema.load({}) + + +class Nested: + def __init__(self, foo): + self.foo = foo + + +class Example: + def __init__(self, nested): + self.nested = nested + + +example = Example(nested=[Nested(x) for x in range(1)]) + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([example, {"foo": 0}, example.nested[0]],), +) +def test_decorator_post_dump_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_dump(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_dump(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.dump(data) == {"nested": [{"foo": 0}]} + + +@pytest.mark.parametrize( + "data,expected_data,expected_original_data", + ([{"nested": [{"foo": 0}]}, {"foo": 0}, {"foo": 0}],), +) +def test_decorator_post_load_with_nested_original_and_pass_many( + data, expected_data, expected_original_data +): + class NestedSchema(Schema): + foo = fields.Int(required=True) + + @post_load(pass_many=False, pass_original=True) + def check_pass_original_when_pass_many_false( + self, data, original_data, **kwargs + ): + assert data == expected_data + assert original_data == expected_original_data + return data + + @post_load(pass_many=True, pass_original=True) + def check_pass_original_when_pass_many_true( + self, data, original_data, many, **kwargs + ): + assert many is True + assert data == [expected_data] + assert original_data == [expected_original_data] + return data + + class ExampleSchema(Schema): + nested = fields.Nested(NestedSchema, required=True, many=True) + + schema = ExampleSchema() + assert schema.load(data) == data diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_deserialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_deserialization.py new file mode 100644 index 0000000000000000000000000000000000000000..80d44272fdc61d6b1dd7273b27312c119e2129cf --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_deserialization.py @@ -0,0 +1,2298 @@ +import datetime as dt +import decimal +import ipaddress +import math +import uuid +from unittest.mock import patch + +import pytest + +from marshmallow import EXCLUDE, INCLUDE, RAISE, Schema, fields, validate +from marshmallow.exceptions import ValidationError +from marshmallow.validate import Equal +from tests.base import ( + ALL_FIELDS, + DateEnum, + GenderEnum, + HairColorEnum, + assert_date_equal, + assert_time_equal, + central, +) + + +class MockDateTimeOverflowError(dt.datetime): + """Used to simulate the possible OverflowError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OverflowError() + + +class MockDateTimeOSError(dt.datetime): + """Used to simulate the possible OSError of datetime.fromtimestamp""" + + def fromtimestamp(self, *args, **kwargs): + raise OSError() + + +class TestDeserializingNone: + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_allow_none_deserialize_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + assert field.deserialize(None) is None + + # https://github.com/marshmallow-code/marshmallow/issues/111 + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_fields_dont_allow_none_by_default(self, FieldClass): + field = FieldClass() + with pytest.raises(ValidationError, match="Field may not be null."): + field.deserialize(None) + + def test_allow_none_is_true_if_missing_is_true(self): + field = fields.Field(load_default=None) + assert field.allow_none is True + assert field.deserialize(None) is None + + def test_list_field_deserialize_none_to_none(self): + field = fields.List(fields.String(allow_none=True), allow_none=True) + assert field.deserialize(None) is None + + def test_tuple_field_deserialize_none_to_none(self): + field = fields.Tuple([fields.String()], allow_none=True) + assert field.deserialize(None) is None + + def test_list_of_nested_allow_none_deserialize_none_to_none(self): + field = fields.List(fields.Nested(Schema(), allow_none=True)) + assert field.deserialize([None]) == [None] + + def test_list_of_nested_non_allow_none_deserialize_none_to_validation_error(self): + field = fields.List(fields.Nested(Schema(), allow_none=False)) + with pytest.raises(ValidationError): + field.deserialize([None]) + + +class TestFieldDeserialization: + def test_float_field_deserialization(self): + field = fields.Float() + assert math.isclose(field.deserialize("12.3"), 12.3) + assert math.isclose(field.deserialize(12.3), 12.3) + + @pytest.mark.parametrize("in_val", ["bad", "", {}, True, False]) + def test_invalid_float_field_deserialization(self, in_val): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + assert excinfo.value.args[0] == "Not a valid number." + + def test_float_field_overflow(self): + field = fields.Float() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(2**1024) + assert excinfo.value.args[0] == "Number too large." + + def test_integer_field_deserialization(self): + field = fields.Integer() + assert field.deserialize("42") == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42.0") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize("bad") + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError): + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid integer." + + def test_strict_integer_field_deserialization(self): + field = fields.Integer(strict=True) + assert field.deserialize(42) == 42 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42.0) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(decimal.Decimal("42.0")) + assert excinfo.value.args[0] == "Not a valid integer." + with pytest.raises(ValidationError) as excinfo: + field.deserialize("42") + assert excinfo.value.args[0] == "Not a valid integer." + + def test_decimal_field_deserialization(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = 3.14 + m5 = "abc" + m6 = [1, 2] + + field = fields.Decimal() + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + assert isinstance(field.deserialize(m4), decimal.Decimal) + assert field.deserialize(m4).as_tuple() == (0, (3, 1, 4), -2) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m6) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.4") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m4) + assert excinfo.value.args[0] == "Not a valid number." + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m5) + assert excinfo.value.args[0] == "Not a valid number." + + def test_decimal_field_with_places_and_rounding(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.3") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_deserialization_string(self): + m1 = 12 + m2 = "12.355" + m3 = decimal.Decimal(1) + m4 = "abc" + m5 = [1, 2] + + field = fields.Decimal(as_string=True) + assert isinstance(field.deserialize(m1), decimal.Decimal) + assert field.deserialize(m1) == decimal.Decimal(12) + assert isinstance(field.deserialize(m2), decimal.Decimal) + assert field.deserialize(m2) == decimal.Decimal("12.355") + assert isinstance(field.deserialize(m3), decimal.Decimal) + assert field.deserialize(m3) == decimal.Decimal(1) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + + def test_decimal_field_special_values(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1d = field.deserialize(m1) + assert isinstance(m1d, decimal.Decimal) + assert m1d.is_qnan() and not m1d.is_signed() + + m2d = field.deserialize(m2) + assert isinstance(m2d, decimal.Decimal) + assert m2d.is_qnan() and not m2d.is_signed() + + m3d = field.deserialize(m3) + assert isinstance(m3d, decimal.Decimal) + assert m3d.is_qnan() and not m3d.is_signed() + + m4d = field.deserialize(m4) + assert isinstance(m4d, decimal.Decimal) + assert m4d.is_qnan() and not m4d.is_signed() + + m5d = field.deserialize(m5) + assert isinstance(m5d, decimal.Decimal) + assert m5d.is_infinite() and m5d.is_signed() + + m6d = field.deserialize(m6) + assert isinstance(m6d, decimal.Decimal) + assert m6d.is_infinite() and not m6d.is_signed() + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + def test_decimal_field_special_values_not_permitted(self): + m1 = "-NaN" + m2 = "NaN" + m3 = "-sNaN" + m4 = "sNaN" + m5 = "-Infinity" + m6 = "Infinity" + m7 = "-0" + + field = fields.Decimal(places=2) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(m1) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + with pytest.raises(ValidationError): + field.deserialize(m2) + with pytest.raises(ValidationError): + field.deserialize(m3) + with pytest.raises(ValidationError): + field.deserialize(m4) + with pytest.raises(ValidationError): + field.deserialize(m5) + with pytest.raises(ValidationError): + field.deserialize(m6) + + m7d = field.deserialize(m7) + assert isinstance(m7d, decimal.Decimal) + assert m7d.is_zero() and m7d.is_signed() + + @pytest.mark.parametrize("allow_nan", (None, False, True)) + @pytest.mark.parametrize("value", ("nan", "-nan", "inf", "-inf")) + def test_float_field_allow_nan(self, value, allow_nan): + if allow_nan is None: + # Test default case is False + field = fields.Float() + else: + field = fields.Float(allow_nan=allow_nan) + + if allow_nan is True: + res = field.deserialize(value) + assert isinstance(res, float) + if value.endswith("nan"): + assert math.isnan(res) + else: + assert res == float(value) + else: + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert str(excinfo.value.args[0]) == ( + "Special numeric values (nan or infinity) are not permitted." + ) + + def test_string_field_deserialization(self): + field = fields.String() + assert field.deserialize("foo") == "foo" + assert field.deserialize(b"foo") == "foo" + + # https://github.com/marshmallow-code/marshmallow/issues/231 + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + assert excinfo.value.args[0] == "Not a valid string." + + with pytest.raises(ValidationError): + field.deserialize({}) + + def test_boolean_field_deserialization(self): + field = fields.Boolean() + assert field.deserialize(True) is True + assert field.deserialize(False) is False + assert field.deserialize("True") is True + assert field.deserialize("False") is False + assert field.deserialize("true") is True + assert field.deserialize("false") is False + assert field.deserialize("1") is True + assert field.deserialize("0") is False + assert field.deserialize("on") is True + assert field.deserialize("ON") is True + assert field.deserialize("On") is True + assert field.deserialize("off") is False + assert field.deserialize("OFF") is False + assert field.deserialize("Off") is False + assert field.deserialize("y") is True + assert field.deserialize("Y") is True + assert field.deserialize("yes") is True + assert field.deserialize("YES") is True + assert field.deserialize("Yes") is True + assert field.deserialize("n") is False + assert field.deserialize("N") is False + assert field.deserialize("no") is False + assert field.deserialize("NO") is False + assert field.deserialize("No") is False + assert field.deserialize(1) is True + assert field.deserialize(0) is False + + with pytest.raises(ValidationError) as excinfo: + field.deserialize({}) + assert excinfo.value.args[0] == "Not a valid boolean." + + with pytest.raises(ValidationError) as excinfo: + field.deserialize(42) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid-string") + + def test_boolean_field_deserialization_with_custom_truthy_values(self): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + assert field.deserialize("yep") is True + + field = fields.Boolean(truthy=("yep",)) + assert field.deserialize("yep") is True + assert field.deserialize(False) is False + + @pytest.mark.parametrize("in_val", ["notvalid", 123]) + def test_boolean_field_deserialization_with_custom_truthy_values_invalid( + self, in_val + ): + class MyBoolean(fields.Boolean): + truthy = {"yep"} + + field = MyBoolean() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field = fields.Boolean(truthy=("yep",)) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_val) + expected_msg = "Not a valid boolean." + assert str(excinfo.value.args[0]) == expected_msg + + field2 = MyBoolean(error_messages={"invalid": "bad input"}) + with pytest.raises(ValidationError) as excinfo: + field2.deserialize(in_val) + assert str(excinfo.value.args[0]) == "bad input" + + field2 = fields.Boolean( + truthy=("yep",), error_messages={"invalid": "bad input"} + ) + + def test_boolean_field_deserialization_with_empty_truthy(self): + field = fields.Boolean(truthy=()) + assert field.deserialize("yep") is True + assert field.deserialize(True) is True + assert field.deserialize(False) is False + + def test_boolean_field_deserialization_with_custom_falsy_values(self): + field = fields.Boolean(falsy=("nope",)) + assert field.deserialize("nope") is False + assert field.deserialize(True) is True + + def test_field_toggle_show_invalid_value_in_error_message(self): + error_messages = {"invalid": "Not valid: {input}"} + boolfield = fields.Boolean(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + boolfield.deserialize("notabool") + assert str(excinfo.value.args[0]) == "Not valid: notabool" + + numfield = fields.Number(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + numfield.deserialize("notanum") + assert str(excinfo.value.args[0]) == "Not valid: notanum" + + intfield = fields.Integer(error_messages=error_messages) + with pytest.raises(ValidationError) as excinfo: + intfield.deserialize("notanint") + assert str(excinfo.value.args[0]) == "Not valid: notanint" + + date_error_messages = {"invalid": "Not a valid {obj_type}: {input}"} + datefield = fields.DateTime(error_messages=date_error_messages) + with pytest.raises(ValidationError) as excinfo: + datefield.deserialize("notadate") + assert str(excinfo.value.args[0]) == "Not a valid datetime: notadate" + + @pytest.mark.parametrize( + "in_value", + [ + "not-a-datetime", + 42, + True, + False, + 0, + "", + [], + "2018", + "2018-01-01", + dt.datetime.now().strftime("%H:%M:%S %Y-%m-%d"), + dt.datetime.now().strftime("%m-%d-%Y %H:%M:%S"), + ], + ) + def test_invalid_datetime_deserialization(self, in_value): + field = fields.DateTime() + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + def test_custom_date_format_datetime_field_deserialization(self): + # Datetime string with format "%H:%M:%S.%f %Y-%m-%d" + datestring = "10:11:12.123456 2019-01-02" + + # Deserialization should fail when datestring is not of same format + field = fields.DateTime(format="%d-%m-%Y %H:%M:%S") + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(datestring) + + field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") + assert field.deserialize(datestring) == dt.datetime( + 2019, 1, 2, 10, 11, 12, 123456 + ) + + field = fields.AwareDateTime(format="%H:%M:%S.%f %Y-%m-%d") + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(datestring) + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ( + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + False, + ), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_rfc_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601"]) + @pytest.mark.parametrize( + ("value", "expected", "aware"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45), False), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + True, + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + True, + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + True, + ), + ], + ) + def test_iso_datetime_field_deserialization(self, fmt, value, expected, aware): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + field = fields.NaiveDateTime(format=fmt) + if aware: + with pytest.raises(ValidationError, match="Not a valid naive datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + field = fields.AwareDateTime(format=fmt) + if not aware: + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + else: + assert field.deserialize(value) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", "1384043025", dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp", 1384043025.12, dt.datetime(2013, 11, 10, 0, 23, 45, 120000)), + ( + "timestamp", + 1384043025.123456, + dt.datetime(2013, 11, 10, 0, 23, 45, 123456), + ), + ("timestamp", 1, dt.datetime(1970, 1, 1, 0, 0, 1)), + ("timestamp_ms", 1384043025000, dt.datetime(2013, 11, 10, 0, 23, 45)), + ("timestamp_ms", 1000, dt.datetime(1970, 1, 1, 0, 0, 1)), + ], + ) + def test_timestamp_field_deserialization(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.deserialize(value) == expected + + # By default, a datetime from a timestamp is never aware. + field = fields.NaiveDateTime(format=fmt) + assert field.deserialize(value) == expected + + field = fields.AwareDateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid aware datetime."): + field.deserialize(value) + + # But it can be added by providing a default. + field = fields.AwareDateTime(format=fmt, default_timezone=central) + expected_aware = expected.replace(tzinfo=central) + assert field.deserialize(value) == expected_aware + + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "in_value", + ["", "!@#", -1, dt.datetime(2013, 11, 10, 1, 23, 45)], + ) + def test_invalid_timestamp_field_deserialization(self, fmt, in_value): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(in_value) + + #  Regression test for https://github.com/marshmallow-code/marshmallow/pull/2102 + @pytest.mark.parametrize("fmt", ["timestamp", "timestamp_ms"]) + @pytest.mark.parametrize( + "mock_fromtimestamp", [MockDateTimeOSError, MockDateTimeOverflowError] + ) + def test_oversized_timestamp_field_deserialization(self, fmt, mock_fromtimestamp): + with patch("datetime.datetime", mock_fromtimestamp): + field = fields.DateTime(format=fmt) + with pytest.raises(ValidationError, match="Not a valid datetime."): + field.deserialize(99999999999999999) + + @pytest.mark.parametrize( + ("fmt", "timezone", "value", "expected"), + [ + ("iso", None, "2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "iso", + dt.timezone.utc, + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "iso", + central, + "2013-11-10T01:23:45-03:00", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ( + "rfc", + None, + "Sun, 10 Nov 2013 01:23:45 -0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + dt.timezone.utc, + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45), + ), + ( + "rfc", + central, + "Sun, 10 Nov 2013 01:23:45 -0300", + dt.datetime(2013, 11, 9, 22, 23, 45), + ), + ], + ) + def test_naive_datetime_with_timezone(self, fmt, timezone, value, expected): + field = fields.NaiveDateTime(format=fmt, timezone=timezone) + assert field.deserialize(value) == expected + + @pytest.mark.parametrize("timezone", (dt.timezone.utc, central)) + @pytest.mark.parametrize( + ("fmt", "value"), + [("iso", "2013-11-10T01:23:45"), ("rfc", "Sun, 10 Nov 2013 01:23:45")], + ) + def test_aware_datetime_default_timezone(self, fmt, timezone, value): + field = fields.AwareDateTime(format=fmt, default_timezone=timezone) + assert field.deserialize(value) == dt.datetime( + 2013, 11, 10, 1, 23, 45, tzinfo=timezone + ) + + def test_time_field_deserialization(self): + field = fields.Time() + t = dt.time(1, 23, 45) + t_formatted = t.isoformat() + result = field.deserialize(t_formatted) + assert isinstance(result, dt.time) + assert_time_equal(result, t) + # With microseconds + t2 = dt.time(1, 23, 45, 6789) + t2_formatted = t2.isoformat() + result2 = field.deserialize(t2_formatted) + assert_time_equal(result2, t2) + + @pytest.mark.parametrize("in_data", ["badvalue", "", [], 42]) + def test_invalid_time_field_deserialization(self, in_data): + field = fields.Time() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_data) + assert excinfo.value.args[0] == "Not a valid time." + + def test_custom_time_format_time_field_deserialization(self): + # Time string with format "%f.%S:%M:%H" + timestring = "123456.12:11:10" + + # Deserialization should fail when timestring is not of same format + field = fields.Time(format="%S:%M:%H") + with pytest.raises(ValidationError, match="Not a valid time."): + field.deserialize(timestring) + + field = fields.Time(format="%f.%S:%M:%H") + assert field.deserialize(timestring) == dt.time(10, 11, 12, 123456) + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("01:23:45", dt.time(1, 23, 45)), + ("01:23:45+01:00", dt.time(1, 23, 45)), + ("01:23:45.123", dt.time(1, 23, 45, 123000)), + ("01:23:45.123456", dt.time(1, 23, 45, 123456)), + ], + ) + def test_iso_time_field_deserialization(self, fmt, value, expected): + if fmt is None: + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.deserialize(value) == expected + + def test_invalid_timedelta_precision(self): + with pytest.raises(ValueError, match='The precision must be "days",'): + fields.TimeDelta("invalid") + + def test_timedelta_field_deserialization(self): + field = fields.TimeDelta() + result = field.deserialize("42") + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 42 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + result = field.deserialize(100000) + assert result.days == 1 + assert result.seconds == 13600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + result = field.deserialize("-42") + assert isinstance(result, dt.timedelta) + assert result.days == -42 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 1 + assert result.microseconds == 1 + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + result = field.deserialize(86400 * 10**6 + 1) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 0 + assert result.microseconds == 1 + + field = fields.TimeDelta() + result = field.deserialize(12.9) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 12 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + result = field.deserialize(1) + assert isinstance(result, dt.timedelta) + assert result.days == 7 + assert result.seconds == 0 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.HOURS) + result = field.deserialize(25) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 3600 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + result = field.deserialize(1441) + assert isinstance(result, dt.timedelta) + assert result.days == 1 + assert result.seconds == 60 + assert result.microseconds == 0 + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + result = field.deserialize(123456) + assert isinstance(result, dt.timedelta) + assert result.days == 0 + assert result.seconds == 123 + assert result.microseconds == 456000 + + total_microseconds_value = 322.0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_microseconds_value + ) + + total_microseconds_value = 322.12345 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + result = field.deserialize(total_microseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, math.floor(total_microseconds_value) + ) + + total_milliseconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + result = field.deserialize(total_milliseconds_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + result.total_seconds() / unit_value, total_milliseconds_value + ) + + total_seconds_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + result = field.deserialize(total_seconds_value) + assert isinstance(result, dt.timedelta) + assert math.isclose(result.total_seconds(), total_seconds_value) + + total_minutes_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + result = field.deserialize(total_minutes_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_minutes_value) + + total_hours_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + result = field.deserialize(total_hours_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_hours_value) + + total_days_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + result = field.deserialize(total_days_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_days_value) + + total_weeks_value = 322.223 + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + result = field.deserialize(total_weeks_value) + assert isinstance(result, dt.timedelta) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose(result.total_seconds() / unit_value, total_weeks_value) + + @pytest.mark.parametrize("in_value", ["", "badvalue", [], 9999999999]) + def test_invalid_timedelta_field_deserialization(self, in_value): + field = fields.TimeDelta(fields.TimeDelta.DAYS) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + assert excinfo.value.args[0] == "Not a valid period of time." + + @pytest.mark.parametrize("format", (None, "%Y-%m-%d")) + def test_date_field_deserialization(self, format): + field = fields.Date(format=format) + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = field.deserialize(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + @pytest.mark.parametrize( + "in_value", ["", 123, [], dt.date(2014, 8, 21).strftime("%d-%m-%Y")] + ) + def test_invalid_date_field_deserialization(self, in_value): + field = fields.Date() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + msg = "Not a valid date." + assert excinfo.value.args[0] == msg + + def test_dict_field_deserialization(self): + data = {"foo": "bar"} + field = fields.Dict() + load = field.deserialize(data) + assert load == {"foo": "bar"} + # Check load is a distinct object + load["foo"] = "baz" + assert data["foo"] == "bar" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("baddict") + assert excinfo.value.args[0] == "Not a valid mapping type." + + def test_structured_dict_value_deserialization(self): + field = fields.Dict(values=fields.List(fields.Str)) + assert field.deserialize({"foo": ["bar", "baz"]}) == {"foo": ["bar", "baz"]} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": [1, 2], "bar": "baz", "ham": ["spam"]}) + assert excinfo.value.args[0] == { + "foo": {"value": {0: ["Not a valid string."], 1: ["Not a valid string."]}}, + "bar": {"value": ["Not a valid list."]}, + } + assert excinfo.value.valid_data == {"foo": [], "ham": ["spam"]} + + def test_structured_dict_key_deserialization(self): + field = fields.Dict(keys=fields.Str) + assert field.deserialize({"foo": "bar"}) == {"foo": "bar"} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar", "foo": "baz"}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {"foo": "baz"} + + def test_structured_dict_key_value_deserialization(self): + field = fields.Dict( + keys=fields.Str( + validate=[validate.Email(), validate.Regexp(r".*@test\.com$")] + ), + values=fields.Decimal, + ) + assert field.deserialize({"foo@test.com": 1}) == { + "foo@test.com": decimal.Decimal(1) + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: "bar"}) + assert excinfo.value.args[0] == { + 1: {"key": ["Not a valid string."], "value": ["Not a valid number."]} + } + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo@test.com": "bar"}) + assert excinfo.value.args[0] == { + "foo@test.com": {"value": ["Not a valid number."]} + } + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({1: 1}) + assert excinfo.value.args[0] == {1: {"key": ["Not a valid string."]}} + assert excinfo.value.valid_data == {} + with pytest.raises(ValidationError) as excinfo: + field.deserialize({"foo": "bar"}) + assert excinfo.value.args[0] == { + "foo": { + "key": [ + "Not a valid email address.", + "String does not match expected pattern.", + ], + "value": ["Not a valid number."], + } + } + assert excinfo.value.valid_data == {} + + def test_url_field_deserialization(self): + field = fields.Url() + assert field.deserialize("https://duckduckgo.com") == "https://duckduckgo.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("badurl") + assert excinfo.value.args[0][0] == "Not a valid URL." + # Relative URLS not allowed by default + with pytest.raises(ValidationError) as excinfo: + field.deserialize("/foo/bar") + assert excinfo.value.args[0][0] == "Not a valid URL." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_url_field_non_list_validators(self): + field = fields.Url(validate=(validate.Length(min=16),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("https://abc.def") + + def test_relative_url_field_deserialization(self): + field = fields.Url(relative=True) + assert field.deserialize("/foo/bar") == "/foo/bar" + + def test_url_field_schemes_argument(self): + field = fields.URL() + url = "ws://test.test" + with pytest.raises(ValidationError): + field.deserialize(url) + field2 = fields.URL(schemes={"http", "https", "ws"}) + assert field2.deserialize(url) == url + + def test_email_field_deserialization(self): + field = fields.Email() + assert field.deserialize("foo@bar.com") == "foo@bar.com" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalidemail") + assert excinfo.value.args[0][0] == "Not a valid email address." + + field = fields.Email(validate=[validate.Length(min=12)]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("foo@bar.com") + assert excinfo.value.args[0][0] == "Shorter than minimum length 12." + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/1400 + def test_email_field_non_list_validators(self): + field = fields.Email(validate=(validate.Length(min=9),)) + with pytest.raises(ValidationError, match="Shorter than minimum length"): + field.deserialize("a@bc.com") + + def test_function_field_deserialization_is_noop_by_default(self): + field = fields.Function(lambda x: None) + # Default is noop + assert field.deserialize("foo") == "foo" + assert field.deserialize(42) == 42 + + def test_function_field_deserialization_with_callable(self): + field = fields.Function(lambda x: None, deserialize=lambda val: val.upper()) + assert field.deserialize("foo") == "FOO" + + def test_function_field_deserialization_with_context(self): + class Parent(Schema): + pass + + field = fields.Function( + lambda x: None, + deserialize=lambda val, context: val.upper() + context["key"], + ) + field.parent = Parent(context={"key": "BAR"}) + assert field.deserialize("foo") == "FOOBAR" + + def test_function_field_passed_deserialize_only_is_load_only(self): + field = fields.Function(deserialize=lambda val: val.upper()) + assert field.load_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_load_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.load_only is False + + def test_uuid_field_deserialization(self): + field = fields.UUID() + uuid_str = str(uuid.uuid4()) + result = field.deserialize(uuid_str) + assert isinstance(result, uuid.UUID) + assert str(result) == uuid_str + + uuid4 = uuid.uuid4() + result = field.deserialize(uuid4) + assert isinstance(result, uuid.UUID) + assert result == uuid4 + + uuid_bytes = b"]\xc7wW\x132O\xf9\xa5\xbe\x13\x1f\x02\x18\xda\xbf" + result = field.deserialize(uuid_bytes) + assert isinstance(result, uuid.UUID) + assert result.bytes == uuid_bytes + + @pytest.mark.parametrize("in_value", ["malformed", 123, [], b"tooshort"]) + def test_invalid_uuid_deserialization(self, in_value): + field = fields.UUID() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid UUID." + + def test_ip_field_deserialization(self): + field = fields.IP() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + @pytest.mark.parametrize( + "in_value", + ["malformed", 123, b"\x01\x02\03", "192.168", "192.168.0.1/24", "ff::aa:1::2"], + ) + def test_invalid_ip_deserialization(self, in_value): + field = fields.IP() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP address." + + def test_ipv4_field_deserialization(self): + field = fields.IPv4() + ipv4_str = "140.82.118.3" + result = field.deserialize(ipv4_str) + assert isinstance(result, ipaddress.IPv4Address) + assert str(result) == ipv4_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/24", + "2a00:1450:4001:81d::200e", + ], + ) + def test_invalid_ipv4_deserialization(self, in_value): + field = fields.IPv4() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 address." + + def test_ipv6_field_deserialization(self): + field = fields.IPv6() + ipv6_str = "2a00:1450:4001:824::200e" + result = field.deserialize(ipv6_str) + assert isinstance(result, ipaddress.IPv6Address) + assert str(result) == ipv6_str + + def test_ipinterface_field_deserialization(self): + field = fields.IPInterface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "ff::aa:1::2", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipinterface_deserialization(self, in_value): + field = fields.IPInterface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IP interface." + + def test_ipv4interface_field_deserialization(self): + field = fields.IPv4Interface() + ipv4interface_str = "140.82.118.3/24" + result = field.deserialize(ipv4interface_str) + assert isinstance(result, ipaddress.IPv4Interface) + assert str(result) == ipv4interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "192.168", + "192.168.0.1/33", + "2a00:1450:4001:81d::200e", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv4interface_deserialization(self, in_value): + field = fields.IPv4Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv4 interface." + + def test_ipv6interface_field_deserialization(self): + field = fields.IPv6Interface() + ipv6interface_str = "2a00:1450:4001:824::200e/128" + result = field.deserialize(ipv6interface_str) + assert isinstance(result, ipaddress.IPv6Interface) + assert str(result) == ipv6interface_str + + @pytest.mark.parametrize( + "in_value", + [ + "malformed", + 123, + b"\x01\x02\03", + "ff::aa:1::2", + "192.168.0.1", + "192.168.0.1/24", + "2a00:1450:4001:824::200e/129", + ], + ) + def test_invalid_ipv6interface_deserialization(self, in_value): + field = fields.IPv6Interface() + with pytest.raises(ValidationError) as excinfo: + field.deserialize(in_value) + + assert excinfo.value.args[0] == "Not a valid IPv6 interface." + + def test_enum_field_by_symbol_deserialization(self): + field = fields.Enum(GenderEnum) + assert field.deserialize("male") == GenderEnum.male + + def test_enum_field_by_symbol_invalid_value(self): + field = fields.Enum(GenderEnum) + with pytest.raises( + ValidationError, match="Must be one of: male, female, non_binary." + ): + field.deserialize("dummy") + + def test_enum_field_by_symbol_not_string(self): + field = fields.Enum(GenderEnum) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + + def test_enum_field_by_value_true_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=True) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=True) + assert field.deserialize(1) == GenderEnum.male + + def test_enum_field_by_value_field_deserialization(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.deserialize("black hair") == HairColorEnum.black + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.deserialize(1) == GenderEnum.male + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.deserialize("29/02/2004") == DateEnum.date_1 + + def test_enum_field_by_value_true_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_invalid_value(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises( + ValidationError, match="Must be one of: 29/02/2004, 29/02/2008, 29/02/2012." + ): + field.deserialize("28/02/2004") + + def test_enum_field_by_value_true_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=True) + with pytest.raises( + ValidationError, + match="Must be one of: black hair, brown hair, blond hair, red hair.", + ): + field.deserialize("dummy") + field = fields.Enum(GenderEnum, by_value=True) + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + field.deserialize(12) + + def test_enum_field_by_value_field_wrong_type(self): + field = fields.Enum(HairColorEnum, by_value=fields.String) + with pytest.raises(ValidationError, match="Not a valid string."): + field.deserialize(12) + field = fields.Enum(GenderEnum, by_value=fields.Integer) + with pytest.raises(ValidationError, match="Not a valid integer."): + field.deserialize("dummy") + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + with pytest.raises(ValidationError, match="Not a valid date."): + field.deserialize("30/02/2004") + + def test_deserialization_function_must_be_callable(self): + with pytest.raises(TypeError): + fields.Function(lambda x: None, deserialize="notvalid") + + def test_method_field_deserialization_is_noop_by_default(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name") + + def uppercase_name(self, obj): + return obj.upper() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("steve") == "steve" + + def test_deserialization_method(self): + class MiniUserSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + def uppercase_name(self, obj): + return obj.name.upper() + + def lowercase_name(self, value): + return value.lower() + + s = MiniUserSchema() + assert s.fields["uppername"].deserialize("STEVE") == "steve" + + def test_deserialization_method_must_be_a_method(self): + class BadSchema(Schema): + uppername = fields.Method("uppercase_name", deserialize="lowercase_name") + + with pytest.raises(AttributeError): + BadSchema() + + def test_method_field_deserialize_only(self): + class MethodDeserializeOnly(Schema): + name = fields.Method(deserialize="lowercase_name") + + def lowercase_name(self, value): + return value.lower() + + assert MethodDeserializeOnly().load({"name": "ALEC"})["name"] == "alec" + + def test_datetime_list_field_deserialization(self): + dtimes = dt.datetime.now(), dt.datetime.now(), dt.datetime.now(dt.timezone.utc) + dstrings = [each.isoformat() for each in dtimes] + field = fields.List(fields.DateTime()) + result = field.deserialize(dstrings) + assert all(isinstance(each, dt.datetime) for each in result) + for actual, expected in zip(result, dtimes): + assert_date_equal(actual, expected) + + def test_list_field_deserialize_invalid_item(self): + field = fields.List(fields.DateTime) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", 42]) + assert excinfo.value.args[0] == {1: ["Not a valid string."]} + + def test_list_field_deserialize_multiple_invalid_items(self): + field = fields.List( + fields.Int( + validate=validate.Range(10, 20, error="Value {input} not in range") + ) + ) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_list_field_deserialize_value_that_is_not_a_list(self, value): + field = fields.List(fields.Str()) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid list." + + def test_datetime_int_tuple_field_deserialization(self): + dtime = dt.datetime.now() + data = dtime.isoformat(), 42 + field = fields.Tuple([fields.DateTime(), fields.Integer()]) + result = field.deserialize(data) + + assert isinstance(result, tuple) + assert len(result) == 2 + for val, type_, true_val in zip(result, (dt.datetime, int), (dtime, 42)): + assert isinstance(val, type_) + assert val == true_val + + def test_tuple_field_deserialize_invalid_item(self): + field = fields.Tuple([fields.DateTime]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["badvalue"]) + assert excinfo.value.args[0] == {0: ["Not a valid datetime."]} + + field = fields.Tuple([fields.Str(), fields.Integer()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(["good", "bad"]) + assert excinfo.value.args[0] == {1: ["Not a valid integer."]} + + def test_tuple_field_deserialize_multiple_invalid_items(self): + validator = validate.Range(10, 20, error="Value {input} not in range") + field = fields.Tuple( + [ + fields.Int(validate=validator), + fields.Int(validate=validator), + fields.Int(validate=validator), + ] + ) + + with pytest.raises(ValidationError) as excinfo: + field.deserialize([10, 5, 25]) + assert len(excinfo.value.args[0]) == 2 + assert excinfo.value.args[0][1] == ["Value 5 not in range"] + assert excinfo.value.args[0][2] == ["Value 25 not in range"] + + @pytest.mark.parametrize("value", ["notalist", 42, {}]) + def test_tuple_field_deserialize_value_that_is_not_a_collection(self, value): + field = fields.Tuple([fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize(value) + assert excinfo.value.args[0] == "Not a valid tuple." + + def test_tuple_field_deserialize_invalid_length(self): + field = fields.Tuple([fields.Str(), fields.Str()]) + with pytest.raises(ValidationError) as excinfo: + field.deserialize([42]) + assert excinfo.value.args[0] == "Length must be 2." + + def test_constant_field_deserialization(self): + field = fields.Constant("something") + assert field.deserialize("whatever") == "something" + + def test_constant_is_always_included_in_deserialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.load({})["foo"] == 42 + assert sch.load({"foo": 24})["foo"] == 42 + + def test_field_deserialization_with_user_validator_function(self): + field = fields.String(validate=lambda s: s.lower() == "valid") + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError) as excinfo: + field.deserialize("invalid") + assert excinfo.value.args[0][0] == "Invalid value." + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validator_class_that_returns_bool(self): + class MyValidator: + def __call__(self, val): + if val == "valid": + return True + return False + + field = fields.Field(validate=MyValidator()) + assert field.deserialize("valid") == "valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_user_validator_that_raises_error_with_list( + self, + ): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + errors = MySchema().validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + def test_validator_must_return_false_to_raise_error(self): + # validator returns None, so anything validates + field = fields.String(validate=lambda s: None) + assert field.deserialize("Valid") == "Valid" + # validator returns False, so nothing validates + field2 = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError): + field2.deserialize("invalid") + + def test_field_deserialization_with_validator_with_nonascii_input(self): + field = fields.String(validate=lambda s: False) + with pytest.raises(ValidationError) as excinfo: + field.deserialize("привет") + assert type(excinfo.value) is ValidationError + + def test_field_deserialization_with_user_validators(self): + validators_gen = ( + func + for func in ( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ) + + m_colletion_type = [ + fields.String( + validate=[ + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ] + ), + fields.String( + validate=( + lambda s: s.lower() == "valid", + lambda s: s.lower()[::-1] == "dilav", + ) + ), + fields.String(validate=validators_gen), + ] + + for field in m_colletion_type: + assert field.deserialize("Valid") == "Valid" + with pytest.raises(ValidationError, match="Invalid value."): + field.deserialize("invalid") + + def test_field_deserialization_with_custom_error_message(self): + field = fields.String( + validate=lambda s: s.lower() == "valid", + error_messages={"validator_failed": "Bad value."}, + ) + with pytest.raises(ValidationError, match="Bad value."): + field.deserialize("invalid") + + +# No custom deserialization behavior, so a dict is returned +class SimpleUserSchema(Schema): + name = fields.String() + age = fields.Float() + + +class Validator(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=lambda n: n > 0) + + +class Validators(Schema): + email = fields.Email() + colors = fields.Str(validate=validate.OneOf(["red", "blue"])) + age = fields.Integer(validate=[lambda n: n > 0, lambda n: n < 100]) + + +class TestSchemaDeserialization: + def test_deserialize_to_dict(self): + user_dict = {"name": "Monty", "age": "42.3"} + result = SimpleUserSchema().load(user_dict) + assert result["name"] == "Monty" + assert math.isclose(result["age"], 42.3) + + def test_deserialize_with_missing_values(self): + user_dict = {"name": "Monty"} + result = SimpleUserSchema().load(user_dict) + # 'age' is not included in result + assert result == {"name": "Monty"} + + def test_deserialize_many(self): + users_data = [{"name": "Mick", "age": "914"}, {"name": "Keith", "age": "8442"}] + result = SimpleUserSchema(many=True).load(users_data) + assert isinstance(result, list) + user = result[0] + assert user["age"] == int(users_data[0]["age"]) + + def test_exclude(self): + schema = SimpleUserSchema(exclude=("age",), unknown=EXCLUDE) + result = schema.load({"name": "Monty", "age": 42}) + assert "name" in result + assert "age" not in result + + def test_nested_single_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, unknown=EXCLUDE) + + blog_dict = { + "title": "Gimme Shelter", + "author": {"name": "Mick", "age": "914", "email": "mick@stones.com"}, + } + result = SimpleBlogSerializer().load(blog_dict) + author = result["author"] + assert author["name"] == "Mick" + assert author["age"] == 914 + assert "email" not in author + + def test_nested_list_deserialization_to_dict(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + authors = fields.Nested(SimpleUserSchema, many=True) + + blog_dict = { + "title": "Gimme Shelter", + "authors": [ + {"name": "Mick", "age": "914"}, + {"name": "Keith", "age": "8442"}, + ], + } + result = SimpleBlogSerializer().load(blog_dict) + assert isinstance(result["authors"], list) + author = result["authors"][0] + assert author["name"] == "Mick" + assert author["age"] == 914 + + def test_nested_single_none_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), allow_none=False) + + sch = OwnerSchema() + errors = sch.validate({"pet": None}) + assert "pet" in errors + assert errors["pet"] == ["Field may not be null."] + + def test_nested_many_non_not_allowed(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, allow_none=False, many=True) + + sch = StoreSchema() + errors = sch.validate({"pets": None}) + assert "pets" in errors + assert errors["pets"] == ["Field may not be null."] + + def test_nested_single_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class OwnerSchema(Schema): + pet = fields.Nested(PetSchema(), required=True) + + sch = OwnerSchema() + errors = sch.validate({}) + assert "pet" in errors + assert errors["pet"] == ["Missing data for required field."] + + def test_nested_many_required_missing(self): + class PetSchema(Schema): + name = fields.Str() + + class StoreSchema(Schema): + pets = fields.Nested(PetSchema, required=True, many=True) + + sch = StoreSchema() + errors = sch.validate({}) + assert "pets" in errors + assert errors["pets"] == ["Missing data for required field."] + + def test_nested_only_basestring(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + child = fields.Pluck(ANestedSchema, "pk") + + sch = MainSchema() + result = sch.load({"pk": "123", "child": "456"}) + assert result["child"]["pk"] == "456" + + def test_nested_only_basestring_with_list_data(self): + class ANestedSchema(Schema): + pk = fields.Str() + + class MainSchema(Schema): + pk = fields.Str() + children = fields.Pluck(ANestedSchema, "pk", many=True) + + sch = MainSchema() + result = sch.load({"pk": "123", "children": ["456", "789"]}) + assert result["children"][0]["pk"] == "456" + assert result["children"][1]["pk"] == "789" + + def test_nested_none_deserialization(self): + class SimpleBlogSerializer(Schema): + title = fields.String() + author = fields.Nested(SimpleUserSchema, allow_none=True) + + blog_dict = {"title": "Gimme Shelter", "author": None} + result = SimpleBlogSerializer().load(blog_dict) + assert result["author"] is None + assert result["title"] == blog_dict["title"] + + def test_deserialize_with_attribute_param(self): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer().load(data) + assert result["email"] == "foo@bar.com" + assert result["age"] == 42 + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/450 + def test_deserialize_with_attribute_param_symmetry(self): + class MySchema(Schema): + foo = fields.Field(attribute="bar.baz") + + schema = MySchema() + dump_data = schema.dump({"bar": {"baz": 42}}) + assert dump_data == {"foo": 42} + + load_data = schema.load({"foo": 42}) + assert load_data == {"bar": {"baz": 42}} + + def test_deserialize_with_attribute_param_error_returns_field_name_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + username = fields.Email(attribute="email") + years = fields.Integer(attribute="age") + + data = {"username": "foobar.com", "years": "42"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["username"] == ["Not a valid email address."] + + def test_deserialize_with_attribute_param_error_returns_data_key_not_attribute_name( + self, + ): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(attribute="age", data_key="Years") + + data = {"Name": "Mick", "UserName": "foobar.com", "Years": "abc"} + with pytest.raises(ValidationError) as excinfo: + AliasingUserSerializer().load(data) + errors = excinfo.value.messages + assert errors["UserName"] == ["Not a valid email address."] + assert errors["Years"] == ["Not a valid integer."] + + def test_deserialize_with_data_key_param(self): + class AliasingUserSerializer(Schema): + name = fields.String(data_key="Name") + username = fields.Email(attribute="email", data_key="UserName") + years = fields.Integer(data_key="Years") + + data = {"Name": "Mick", "UserName": "foo@bar.com", "years": "42"} + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert result["email"] == "foo@bar.com" + assert "years" not in result + + def test_deserialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.load({"": "Grace"}) == {"name": "Grace"} + + def test_deserialize_with_dump_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(dump_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), dump_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer(unknown=EXCLUDE).load(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_deserialize_with_missing_param_value(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_callable(self): + bdate = dt.datetime(2017, 9, 29) + + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(load_default=lambda: bdate) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["birthdate"] == bdate + + def test_deserialize_with_missing_param_none(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_default=None, allow_none=True) + + data = {"name": "Mick"} + result = AliasingUserSerializer().load(data) + assert result["name"] == "Mick" + assert result["years"] is None + + def test_deserialization_raises_with_errors(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validator() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_raises_with_errors_with_multiple_validators(self): + bad_data = {"email": "invalid-email", "colors": "burger", "age": -1} + v = Validators() + with pytest.raises(ValidationError) as excinfo: + v.load(bad_data) + errors = excinfo.value.messages + assert "email" in errors + assert "colors" in errors + assert "age" in errors + + def test_deserialization_many_raises_errors(self): + bad_data = [ + {"email": "foo@bar.com", "colors": "red", "age": 18}, + {"email": "bad", "colors": "pizza", "age": -1}, + ] + v = Validator(many=True) + with pytest.raises(ValidationError): + v.load(bad_data) + + def test_validation_errors_are_stored(self): + def validate_field(val): + raise ValidationError("Something went wrong") + + class MySchema(Schema): + foo = fields.Field(validate=validate_field) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + errors = excinfo.value.messages + assert "Something went wrong" in errors["foo"] + + def test_multiple_errors_can_be_stored_for_a_field(self): + def validate_with_bool(n): + return False + + def validate_with_error(n): + raise ValidationError("foo is not valid") + + class MySchema(Schema): + foo = fields.Field( + required=True, validate=[validate_with_bool, validate_with_error] + ) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": "bar"}) + errors = excinfo.value.messages + + assert type(errors["foo"]) is list + assert len(errors["foo"]) == 2 + + def test_multiple_errors_can_be_stored_for_an_email_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + email = fields.Email(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"email": "foo"}) + errors = excinfo.value.messages + assert len(errors["email"]) == 2 + assert "Not a valid email address." in errors["email"][0] + + def test_multiple_errors_can_be_stored_for_a_url_field(self): + def validate_with_bool(val): + return False + + class MySchema(Schema): + url = fields.Url(validate=[validate_with_bool]) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"url": "foo"}) + errors = excinfo.value.messages + assert len(errors["url"]) == 2 + assert "Not a valid URL." in errors["url"][0] + + def test_required_value_only_passed_to_validators_if_provided(self): + class MySchema(Schema): + foo = fields.Field(required=True, validate=lambda f: False) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({}) + errors = excinfo.value.messages + # required value missing + assert len(errors["foo"]) == 1 + assert "Missing data for required field." in errors["foo"] + + @pytest.mark.parametrize("partial_schema", [True, False]) + def test_partial_deserialization(self, partial_schema): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + + schema_args = {} + load_args = {} + if partial_schema: + schema_args["partial"] = True + else: + load_args["partial"] = True + data = MySchema(**schema_args).load({"foo": 3}, **load_args) + + assert data["foo"] == 3 + assert "bar" not in data + + def test_partial_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3}, partial=tuple()) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["foo"] == 3 + assert "bar" in errors + assert "baz" in errors + + data = MySchema().load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + data = MySchema(partial=True).load({"foo": 3}, partial=("bar", "baz")) + assert data["foo"] == 3 + assert "bar" not in data + assert "baz" not in data + + def test_partial_fields_validation(self): + class MySchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field(required=True) + baz = fields.Field(required=True) + + errors = MySchema().validate({"foo": 3}, partial=tuple()) + assert "bar" in errors + assert "baz" in errors + + errors = MySchema().validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + errors = MySchema(partial=True).validate({"foo": 3}, partial=("bar", "baz")) + assert errors == {} + + def test_unknown_fields_deserialization(self): + class MySchema(Schema): + foo = fields.Integer() + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=INCLUDE) + assert data["foo"] == 3 + assert data["bar"] + + data = MySchema(unknown=INCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] + + with pytest.raises(ValidationError, match="foo"): + MySchema(unknown=INCLUDE).load({"foo": "asd", "bar": 5}) + + data = MySchema(unknown=INCLUDE, many=True).load( + [{"foo": 1}, {"foo": 3, "bar": 5}] + ) + assert "foo" in data[1] + assert "bar" in data[1] + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 3, "bar": 5}) + err = excinfo.value + assert "bar" in err.messages + assert err.messages["bar"] == ["Unknown field."] + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "abc"}, {"foo": 3, "bar": 5}]) + err = excinfo.value + assert 0 in err.messages + assert "foo" in err.messages[0] + assert err.messages[0]["foo"] == ["Not a valid integer."] + assert 1 in err.messages + assert "bar" in err.messages[1] + assert err.messages[1]["bar"] == ["Unknown field."] + + def test_unknown_fields_deserialization_precedence(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Integer() + + data = MySchema().load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert data["bar"] == 5 + + data = MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}) + assert data["foo"] == 3 + assert "bar" not in data + + data = MySchema().load({"foo": 3, "bar": 5}, unknown=EXCLUDE) + assert data["foo"] == 3 + assert "bar" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=EXCLUDE).load({"foo": 3, "bar": 5}, unknown=RAISE) + + def test_unknown_fields_deserialization_with_data_key(self): + class MySchema(Schema): + foo = fields.Integer(data_key="Foo") + + data = MySchema().load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + data = MySchema(unknown=RAISE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + with pytest.raises(ValidationError): + MySchema(unknown=RAISE).load({"foo": 1}) + + data = MySchema(unknown=INCLUDE).load({"Foo": 1}) + assert data["foo"] == 1 + assert "Foo" not in data + + def test_unknown_fields_deserialization_with_index_errors_false(self): + class MySchema(Schema): + foo = fields.Integer() + + class Meta: + unknown = RAISE + index_errors = False + + with pytest.raises(ValidationError) as excinfo: + MySchema(many=True).load([{"foo": "invalid"}, {"foo": 42, "bar": 24}]) + err = excinfo.value + assert 1 not in err.messages + assert "foo" in err.messages + assert "bar" in err.messages + assert err.messages["foo"] == ["Not a valid integer."] + assert err.messages["bar"] == ["Unknown field."] + + def test_dump_only_fields_considered_unknown(self): + class MySchema(Schema): + foo = fields.Int(dump_only=True) + + with pytest.raises(ValidationError) as excinfo: + MySchema().load({"foo": 42}) + err = excinfo.value + assert "foo" in err.messages + assert err.messages["foo"] == ["Unknown field."] + + # When unknown = INCLUDE, dump-only fields are included as unknown + # without any validation. + data = MySchema(unknown=INCLUDE).load({"foo": "LOL"}) + assert data["foo"] == "LOL" + + def test_unknown_fields_do_not_unpack_dotted_names(self): + class MySchema(Schema): + class Meta: + unknown = INCLUDE + + foo = fields.Str() + bar = fields.Str(data_key="bar.baz") + + # dotted names are still supported + data = MySchema().load({"foo": "hi", "bar.baz": "okay"}) + assert data == {"foo": "hi", "bar": "okay"} + + # but extra keys included via unknown=INCLUDE are not transformed into nested dicts + data = MySchema().load({"foo": "hi", "bar.baz": "okay", "alpha.beta": "woah!"}) + assert data == {"foo": "hi", "bar": "okay", "alpha.beta": "woah!"} + + +validators_gen = (func for func in [lambda x: x <= 24, lambda x: 18 <= x]) + +validators_gen_float = (func for func in [lambda f: f <= 4.1, lambda f: f >= 1.0]) + +validators_gen_str = ( + func for func in [lambda n: len(n) == 3, lambda n: n[1].lower() == "o"] +) + + +class TestValidation: + def test_integer_with_validator(self): + field = fields.Integer(validate=lambda x: 18 <= x <= 24) + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Integer(validate=[lambda x: x <= 24, lambda x: 18 <= x]), + fields.Integer(validate=(lambda x: x <= 24, lambda x: 18 <= x)), + fields.Integer(validate=validators_gen), + ], + ) + def test_integer_with_validators(self, field): + out = field.deserialize("20") + assert out == 20 + with pytest.raises(ValidationError): + field.deserialize(25) + + @pytest.mark.parametrize( + "field", + [ + fields.Float(validate=[lambda f: f <= 4.1, lambda f: f >= 1.0]), + fields.Float(validate=(lambda f: f <= 4.1, lambda f: f >= 1.0)), + fields.Float(validate=validators_gen_float), + ], + ) + def test_float_with_validators(self, field): + assert field.deserialize(3.14) + with pytest.raises(ValidationError): + field.deserialize(4.2) + + def test_string_validator(self): + field = fields.String(validate=lambda n: len(n) == 3) + assert field.deserialize("Joe") == "Joe" + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_function_validator(self): + field = fields.Function( + lambda d: d.name.upper(), validate=lambda n: len(n) == 3 + ) + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + @pytest.mark.parametrize( + "field", + [ + fields.Function( + lambda d: d.name.upper(), + validate=[lambda n: len(n) == 3, lambda n: n[1].lower() == "o"], + ), + fields.Function( + lambda d: d.name.upper(), + validate=(lambda n: len(n) == 3, lambda n: n[1].lower() == "o"), + ), + fields.Function(lambda d: d.name.upper(), validate=validators_gen_str), + ], + ) + def test_function_validators(self, field): + assert field.deserialize("joe") + with pytest.raises(ValidationError): + field.deserialize("joseph") + + def test_method_validator(self): + class MethodSerializer(Schema): + name = fields.Method( + "get_name", deserialize="get_name", validate=lambda n: len(n) == 3 + ) + + def get_name(self, val): + return val.upper() + + assert MethodSerializer().load({"name": "joe"}) + with pytest.raises(ValidationError, match="Invalid value."): + MethodSerializer().load({"name": "joseph"}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/269 + def test_nested_data_is_stored_when_validation_fails(self): + class SchemaA(Schema): + x = fields.Integer() + y = fields.Integer(validate=lambda n: n > 0) + z = fields.Integer() + + class SchemaB(Schema): + w = fields.Integer() + n = fields.Nested(SchemaA) + + sch = SchemaB() + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": 89, "z": None}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "z" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "y": 89}} + + with pytest.raises(ValidationError) as excinfo: + sch.load({"w": 90, "n": {"x": 90, "y": -1, "z": 180}}) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "y" in errors["n"] + assert data == {"w": 90, "n": {"x": 90, "z": 180}} + + def test_false_value_validation(self): + class Sch(Schema): + lamb = fields.Raw(validate=lambda x: x is False) + equal = fields.Raw(validate=Equal(False)) + + errors = Sch().validate({"lamb": False, "equal": False}) + assert not errors + errors = Sch().validate({"lamb": True, "equal": True}) + assert "lamb" in errors + assert errors["lamb"] == ["Invalid value."] + assert "equal" in errors + assert errors["equal"] == ["Must be equal to False."] + + def test_nested_partial_load(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # Partial loading shouldn't generate any errors. + result = SchemaB().load(b_dict, partial=True) + assert result["z"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaB().load(b_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["z"]["y"] == 42 + assert "z" in errors + assert "x" in errors["z"] + + def test_deeply_nested_partial_load(self): + class SchemaC(Schema): + x = fields.Integer(required=True) + y = fields.Integer() + + class SchemaB(Schema): + c = fields.Nested(SchemaC) + + class SchemaA(Schema): + b = fields.Nested(SchemaB) + + a_dict = {"b": {"c": {"y": 42}}} + # Partial loading shouldn't generate any errors. + result = SchemaA().load(a_dict, partial=True) + assert result["b"]["c"]["y"] == 42 + # Non partial loading should complain about missing values. + with pytest.raises(ValidationError) as excinfo: + SchemaA().load(a_dict) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert data["b"]["c"]["y"] == 42 + assert "b" in errors + assert "c" in errors["b"] + assert "x" in errors["b"]["c"] + + def test_nested_partial_tuple(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA) + + b_dict = {"z": {"y": 42}} + # If we ignore the missing z.x, z.y should still load. + result = SchemaB().load(b_dict, partial=("z.x",)) + assert result["z"]["y"] == 42 + # If we ignore a missing z.y we should get a validation error. + with pytest.raises(ValidationError): + SchemaB().load(b_dict, partial=("z.y",)) + + def test_nested_partial_default(self): + class SchemaA(Schema): + x = fields.Integer(required=True) + y = fields.Integer(required=True) + + class SchemaB(Schema): + z = fields.Nested(SchemaA(partial=("x",))) + + b_dict = {"z": {"y": 42}} + # Nested partial args should be respected. + result = SchemaB().load(b_dict) + assert result["z"]["y"] == 42 + with pytest.raises(ValidationError): + SchemaB().load({"z": {"x": 0}}) + + +@pytest.mark.parametrize("FieldClass", ALL_FIELDS) +def test_required_field_failure(FieldClass): # noqa + class RequireSchema(Schema): + age = FieldClass(required=True) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + assert "Missing data for required field." in errors["age"] + + +@pytest.mark.parametrize( + "message", + [ + "My custom required message", + {"error": "something", "code": 400}, + ["first error", "second error"], + ], +) +def test_required_message_can_be_changed(message): + class RequireSchema(Schema): + age = fields.Integer(required=True, error_messages={"required": message}) + + user_data = {"name": "Phil"} + with pytest.raises(ValidationError) as excinfo: + RequireSchema().load(user_data) + errors = excinfo.value.messages + expected = [message] if isinstance(message, str) else message + assert expected == errors["age"] + + +@pytest.mark.parametrize("unknown", (EXCLUDE, INCLUDE, RAISE)) +@pytest.mark.parametrize("data", [True, False, 42, None, []]) +def test_deserialize_raises_exception_if_input_type_is_incorrect(data, unknown): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + + with pytest.raises(ValidationError, match="Invalid input type.") as excinfo: + MySchema(unknown=unknown).load(data) + exc = excinfo.value + assert list(exc.messages.keys()) == ["_schema"] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_error_store.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_error_store.py new file mode 100644 index 0000000000000000000000000000000000000000..8315bf2a93caacb0026c4dab6fd395e9b7a56e30 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_error_store.py @@ -0,0 +1,143 @@ +from collections import namedtuple + +from marshmallow import missing +from marshmallow.error_store import merge_errors + + +def test_missing_is_falsy(): + assert bool(missing) is False + + +CustomError = namedtuple("CustomError", ["code", "message"]) + + +class TestMergeErrors: + def test_merging_none_and_string(self): + assert "error1" == merge_errors(None, "error1") + + def test_merging_none_and_custom_error(self): + assert CustomError(123, "error1") == merge_errors( + None, CustomError(123, "error1") + ) + + def test_merging_none_and_list(self): + assert ["error1", "error2"] == merge_errors(None, ["error1", "error2"]) + + def test_merging_none_and_dict(self): + assert {"field1": "error1"} == merge_errors(None, {"field1": "error1"}) + + def test_merging_string_and_none(self): + assert "error1" == merge_errors("error1", None) + + def test_merging_custom_error_and_none(self): + assert CustomError(123, "error1") == merge_errors( + CustomError(123, "error1"), None + ) + + def test_merging_list_and_none(self): + assert ["error1", "error2"] == merge_errors(["error1", "error2"], None) + + def test_merging_dict_and_none(self): + assert {"field1": "error1"} == merge_errors({"field1": "error1"}, None) + + def test_merging_string_and_string(self): + assert ["error1", "error2"] == merge_errors("error1", "error2") + + def test_merging_custom_error_and_string(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), "error2" + ) + + def test_merging_string_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + "error1", CustomError(123, "error2") + ) + + def test_merging_custom_error_and_custom_error(self): + assert [CustomError(123, "error1"), CustomError(456, "error2")] == merge_errors( + CustomError(123, "error1"), CustomError(456, "error2") + ) + + def test_merging_string_and_list(self): + assert ["error1", "error2"] == merge_errors("error1", ["error2"]) + + def test_merging_string_and_dict(self): + assert {"_schema": "error1", "field1": "error2"} == merge_errors( + "error1", {"field1": "error2"} + ) + + def test_merging_string_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + "error1", {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_custom_error_and_list(self): + assert [CustomError(123, "error1"), "error2"] == merge_errors( + CustomError(123, "error1"), ["error2"] + ) + + def test_merging_custom_error_and_dict(self): + assert { + "_schema": CustomError(123, "error1"), + "field1": "error2", + } == merge_errors(CustomError(123, "error1"), {"field1": "error2"}) + + def test_merging_custom_error_and_dict_with_schema_error(self): + assert { + "_schema": [CustomError(123, "error1"), "error2"], + "field1": "error3", + } == merge_errors( + CustomError(123, "error1"), {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_list_and_string(self): + assert ["error1", "error2"] == merge_errors(["error1"], "error2") + + def test_merging_list_and_custom_error(self): + assert ["error1", CustomError(123, "error2")] == merge_errors( + ["error1"], CustomError(123, "error2") + ) + + def test_merging_list_and_list(self): + assert ["error1", "error2"] == merge_errors(["error1"], ["error2"]) + + def test_merging_list_and_dict(self): + assert {"_schema": ["error1"], "field1": "error2"} == merge_errors( + ["error1"], {"field1": "error2"} + ) + + def test_merging_list_and_dict_with_schema_error(self): + assert {"_schema": ["error1", "error2"], "field1": "error3"} == merge_errors( + ["error1"], {"_schema": "error2", "field1": "error3"} + ) + + def test_merging_dict_and_string(self): + assert {"_schema": "error2", "field1": "error1"} == merge_errors( + {"field1": "error1"}, "error2" + ) + + def test_merging_dict_and_custom_error(self): + assert { + "_schema": CustomError(123, "error2"), + "field1": "error1", + } == merge_errors({"field1": "error1"}, CustomError(123, "error2")) + + def test_merging_dict_and_list(self): + assert {"_schema": ["error2"], "field1": "error1"} == merge_errors( + {"field1": "error1"}, ["error2"] + ) + + def test_merging_dict_and_dict(self): + assert { + "field1": "error1", + "field2": ["error2", "error3"], + "field3": "error4", + } == merge_errors( + {"field1": "error1", "field2": "error2"}, + {"field2": "error3", "field3": "error4"}, + ) + + def test_deep_merging_dicts(self): + assert {"field1": {"field2": ["error1", "error2"]}} == merge_errors( + {"field1": {"field2": "error1"}}, {"field1": {"field2": "error2"}} + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_exceptions.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..e4f144a118b9c11eed490ba76159d2a152110f2f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,42 @@ +import pytest + +from marshmallow.exceptions import ValidationError + + +class TestValidationError: + def test_stores_message_in_list(self): + err = ValidationError("foo") + assert err.messages == ["foo"] + + def test_can_pass_list_of_messages(self): + err = ValidationError(["foo", "bar"]) + assert err.messages == ["foo", "bar"] + + def test_stores_dictionaries(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages == messages + + def test_can_store_field_name(self): + err = ValidationError("invalid email", field_name="email") + assert err.field_name == "email" + + def test_str(self): + err = ValidationError("invalid email") + assert str(err) == "invalid email" + + err2 = ValidationError("invalid email", "email") + assert str(err2) == "invalid email" + + def test_stores_dictionaries_in_messages_dict(self): + messages = {"user": {"email": ["email is invalid"]}} + err = ValidationError(messages) + assert err.messages_dict == messages + + def test_messages_dict_type_error_on_badval(self): + err = ValidationError("foo") + with pytest.raises(TypeError) as excinfo: + err.messages_dict # noqa: B018 + assert "cannot access 'messages_dict' when 'messages' is of type list" in str( + excinfo.value + ) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_fields.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_fields.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1d463860ecf68fba1e26bacbcb705d093ab7e3 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_fields.py @@ -0,0 +1,665 @@ +import pytest + +from marshmallow import ( + EXCLUDE, + INCLUDE, + RAISE, + Schema, + ValidationError, + fields, + missing, +) +from marshmallow.exceptions import StringNotCollectionError +from marshmallow.orderedset import OrderedSet +from tests.base import ALL_FIELDS + + +@pytest.mark.parametrize( + ("alias", "field"), + [ + (fields.Int, fields.Integer), + (fields.Str, fields.String), + (fields.Bool, fields.Boolean), + (fields.URL, fields.Url), + ], +) +def test_field_aliases(alias, field): + assert alias is field + + +class TestField: + def test_repr(self): + default = "œ∑´" + field = fields.Field(dump_default=default, attribute=None) + assert repr(field) == ( + f"" + ) + int_field = fields.Integer(validate=lambda x: True) + assert " 3) + bar = fields.Int(validate=lambda x: x > 3) + + sch = MySchema() + valid = {"foo": "loll", "bar": 42} + invalid = {"foo": "lol", "bar": 3} + errors = sch.validate([valid, invalid], many=True) + + assert 1 in errors + assert len(errors[1]) == 2 + assert "foo" in errors[1] + assert "bar" in errors[1] + + +def test_dump_returns_a_dict(user): + s = UserSchema() + result = s.dump(user) + assert type(result) is dict + + +def test_dumps_returns_a_string(user): + s = UserSchema() + result = s.dumps(user) + assert type(result) is str + + +def test_dumping_single_object_with_collection_schema(user): + s = UserSchema(many=True) + result = s.dump(user, many=False) + assert type(result) is dict + assert result == UserSchema().dump(user) + + +def test_loading_single_object_with_collection_schema(): + s = UserSchema(many=True) + in_data = {"name": "Mick", "email": "mick@stones.com"} + result = s.load(in_data, many=False) + assert type(result) is User + assert result.name == UserSchema().load(in_data).name + + +def test_dumps_many(): + s = UserSchema() + u1, u2 = User("Mick"), User("Keith") + json_result = s.dumps([u1, u2], many=True) + data = json.loads(json_result) + assert len(data) == 2 + assert data[0] == s.dump(u1) + + +def test_load_returns_an_object(): + s = UserSchema() + result = s.load({"name": "Monty"}) + assert type(result) is User + + +def test_load_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + result = s.load(in_data, many=True) + assert type(result) is list + assert type(result[0]) is User + assert result[0].name == "Mick" + + +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), [], set(), "lol")) +def test_load_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch().load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == {} + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/906 +@pytest.mark.parametrize("val", (None, False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_invalid_input_type(val): + class Sch(Schema): + name = fields.Str() + + with pytest.raises(ValidationError) as e: + Sch(many=True).load(val) + assert e.value.messages == {"_schema": ["Invalid input type."]} + assert e.value.valid_data == [] + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_empty_collection(val): + class Sch(Schema): + name = fields.Str() + + assert Sch(many=True).load(val) == [] + + +@pytest.mark.parametrize("val", (False, 1, 1.2, object(), {}, {"1": 2}, "lol")) +def test_load_many_in_nested_invalid_input_type(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + with pytest.raises(ValidationError) as e: + Outer().load({"list1": val, "list2": val}) + # TODO: Error messages should be identical (#779) + assert e.value.messages == { + "list1": ["Not a valid list."], + "list2": ["Invalid type."], + } + + +@pytest.mark.parametrize("val", ([], set())) +def test_load_many_in_nested_empty_collection(val): + class Inner(Schema): + name = fields.String() + + class Outer(Schema): + list1 = fields.List(fields.Nested(Inner)) + list2 = fields.Nested(Inner, many=True) + + assert Outer().load({"list1": val, "list2": val}) == {"list1": [], "list2": []} + + +def test_loads_returns_a_user(): + s = UserSchema() + result = s.loads(json.dumps({"name": "Monty"})) + assert type(result) is User + + +def test_loads_many(): + s = UserSchema() + in_data = [{"name": "Mick"}, {"name": "Keith"}] + in_json_data = json.dumps(in_data) + result = s.loads(in_json_data, many=True) + assert type(result) is list + assert result[0].name == "Mick" + + +def test_loads_deserializes_from_json(): + user_dict = {"name": "Monty", "age": "42.3"} + user_json = json.dumps(user_dict) + result = UserSchema().loads(user_json) + assert isinstance(result, User) + assert result.name == "Monty" + assert math.isclose(result.age, 42.3) + + +def test_serializing_none(): + class MySchema(Schema): + id = fields.Str(dump_default="no-id") + num = fields.Int() + name = fields.Str() + + data = UserSchema().dump(None) + assert data == {"id": "no-id"} + + +def test_default_many_symmetry(): + """The dump/load(s) methods should all default to the many value of the schema.""" + s_many = UserSchema(many=True, only=("name",)) + s_single = UserSchema(only=("name",)) + u1, u2 = User("King Arthur"), User("Sir Lancelot") + s_single.load(s_single.dump(u1)) + s_single.loads(s_single.dumps(u1)) + s_many.load(s_many.dump([u1, u2])) + s_many.loads(s_many.dumps([u1, u2])) + + +def test_on_bind_field_hook(): + class MySchema(Schema): + foo = fields.Str() + + def on_bind_field(self, field_name, field_obj): + assert field_obj.parent is self + field_obj.metadata["fname"] = field_name + + schema = MySchema() + assert schema.fields["foo"].metadata["fname"] == "foo" + + +def test_nested_on_bind_field_hook(): + class MySchema(Schema): + class NestedSchema(Schema): + bar = fields.Str() + + def on_bind_field(self, field_name, field_obj): + field_obj.metadata["fname"] = self.context["fname"] + + foo = fields.Nested(NestedSchema) + + schema1 = MySchema(context={"fname": "foobar"}) + schema2 = MySchema(context={"fname": "quxquux"}) + + assert schema1.fields["foo"].schema.fields["bar"].metadata["fname"] == "foobar" + assert schema2.fields["foo"].schema.fields["bar"].metadata["fname"] == "quxquux" + + +class TestValidate: + def test_validate_raises_with_errors_dict(self): + s = UserSchema() + errors = s.validate({"email": "bad-email", "name": "Valid Name"}) + assert type(errors) is dict + assert "email" in errors + assert "name" not in errors + + valid_data = {"name": "Valid Name", "email": "valid@email.com"} + errors = s.validate(valid_data) + assert errors == {} + + def test_validate_many(self): + s = UserSchema(many=True) + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 in errors + assert "email" in errors[1] + + def test_validate_many_doesnt_store_index_if_index_errors_option_is_false(self): + class NoIndex(Schema): + email = fields.Email() + + class Meta: + index_errors = False + + s = NoIndex() + in_data = [ + {"name": "Valid Name", "email": "validemail@hotmail.com"}, + {"name": "Valid Name2", "email": "invalid"}, + ] + errors = s.validate(in_data, many=True) + assert 1 not in errors + assert "email" in errors + + def test_validate(self): + s = UserSchema() + errors = s.validate({"email": "bad-email"}) + assert errors == {"email": ["Not a valid email address."]} + + def test_validate_required(self): + class MySchema(Schema): + foo = fields.Field(required=True) + + s = MySchema() + errors = s.validate({"bar": 42}) + assert "foo" in errors + assert "required" in errors["foo"][0] + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_fields_are_not_copies(SchemaClass): + s = SchemaClass() + s2 = SchemaClass() + assert s.fields is not s2.fields + + +def test_dumps_returns_json(user): + ser = UserSchema() + serialized = ser.dump(user) + json_data = ser.dumps(user) + assert type(json_data) is str + expected = json.dumps(serialized) + assert json_data == expected + + +def test_naive_datetime_field(user, serialized_user): + expected = utils.isoformat(user.created) + assert serialized_user["created"] == expected + + +def test_datetime_formatted_field(user, serialized_user): + result = serialized_user["created_formatted"] + assert result == user.created.strftime("%Y-%m-%d") + + +def test_datetime_iso_field(user, serialized_user): + assert serialized_user["created_iso"] == utils.isoformat(user.created) + + +def test_tz_datetime_field(user, serialized_user): + # Datetime is corrected back to GMT + expected = utils.isoformat(user.updated) + assert serialized_user["updated"] == expected + + +def test_class_variable(serialized_user): + assert serialized_user["species"] == "Homo sapiens" + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serialize_many(SchemaClass): + user1 = User(name="Mick", age=123) + user2 = User(name="Keith", age=456) + users = [user1, user2] + serialized = SchemaClass(many=True).dump(users) + assert len(serialized) == 2 + assert serialized[0]["name"] == "Mick" + assert serialized[1]["name"] == "Keith" + + +def test_inheriting_schema(user): + sch = ExtendedUserSchema() + result = sch.dump(user) + assert result["name"] == user.name + user.is_old = True + result = sch.dump(user) + assert result["is_old"] is True + + +def test_custom_field(serialized_user, user): + assert serialized_user["uppername"] == user.name.upper() + + +def test_url_field(serialized_user, user): + assert serialized_user["homepage"] == user.homepage + + +def test_relative_url_field(): + u = {"name": "John", "homepage": "/foo"} + UserRelativeUrlSchema().load(u) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_stores_invalid_url_error(SchemaClass): + user = {"name": "Steve", "homepage": "www.foo.com"} + with pytest.raises(ValidationError) as excinfo: + SchemaClass().load(user) + errors = excinfo.value.messages + assert "homepage" in errors + expected = ["Not a valid URL."] + assert errors["homepage"] == expected + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_email_field(SchemaClass): + u = User("John", email="john@example.com") + s = SchemaClass().dump(u) + assert s["email"] == "john@example.com" + + +def test_stored_invalid_email(): + u = {"name": "John", "email": "johnexample.com"} + with pytest.raises(ValidationError) as excinfo: + UserSchema().load(u) + errors = excinfo.value.messages + assert "email" in errors + assert errors["email"][0] == "Not a valid email address." + + +def test_integer_field(): + u = User("John", age=42.3) + serialized = UserIntSchema().dump(u) + assert type(serialized["age"]) is int + assert serialized["age"] == 42 + + +def test_as_string(): + u = User("John", age=42.3) + serialized = UserFloatStringSchema().dump(u) + assert type(serialized["age"]) is str + assert math.isclose(float(serialized["age"]), 42.3) + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_method_field(SchemaClass, serialized_user): + assert serialized_user["is_old"] is False + u = User("Joe", age=81) + assert SchemaClass().dump(u)["is_old"] is True + + +def test_function_field(serialized_user, user): + assert serialized_user["lowername"] == user.name.lower() + + +def test_fields_must_be_declared_as_instances(user): + class BadUserSchema(Schema): + name = fields.String + + with pytest.raises( + TypeError, match='Field for "name" must be declared as a Field instance' + ): + BadUserSchema().dump(user) + + +# regression test +def test_bind_field_does_not_swallow_typeerror(): + class MySchema(Schema): + name = fields.Str() + + def on_bind_field(self, field_name, field_obj): + raise TypeError("boom") + + with pytest.raises(TypeError, match="boom"): + MySchema() + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_serializing_generator(SchemaClass): + users = [User("Foo"), User("Bar")] + user_gen = (u for u in users) + s = SchemaClass(many=True).dump(user_gen) + assert len(s) == 2 + assert s[0] == SchemaClass().dump(users[0]) + + +def test_serializing_empty_list_returns_empty_list(): + assert UserSchema(many=True).dump([]) == [] + assert UserMetaSchema(many=True).dump([]) == [] + + +def test_serializing_dict(): + user = { + "name": "foo", + "email": "foo@bar.com", + "age": 42, + "various_data": {"foo": "bar"}, + } + data = UserSchema().dump(user) + assert data["name"] == "foo" + assert data["age"] == 42 + assert data["various_data"] == {"foo": "bar"} + + +def test_serializing_dict_with_meta_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo", "bar") + + sch = MySchema() + data = sch.dump({"foo": 42, "bar": 24, "baz": 424}) + assert data["foo"] == 42 + assert data["bar"] == 24 + assert "baz" not in data + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_exclude_in_init(SchemaClass, user): + s = SchemaClass(exclude=("age", "homepage")).dump(user) + assert "homepage" not in s + assert "age" not in s + assert "name" in s + + +@pytest.mark.parametrize("SchemaClass", [UserSchema, UserMetaSchema]) +def test_only_in_init(SchemaClass, user): + s = SchemaClass(only=("name", "age")).dump(user) + assert "homepage" not in s + assert "name" in s + assert "age" in s + + +def test_invalid_only_param(user): + with pytest.raises(ValueError): + UserSchema(only=("_invalid", "name")).dump(user) + + +def test_can_serialize_uuid(serialized_user, user): + assert serialized_user["uid"] == str(user.uid) + + +def test_can_serialize_time(user, serialized_user): + expected = user.time_registered.isoformat()[:15] + assert serialized_user["time_registered"] == expected + + +def test_json_module_is_deprecated(): + with pytest.deprecated_call(): + + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + json_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_render_module(): + class UserJSONSchema(Schema): + name = fields.String() + + class Meta: + render_module = mockjson + + user = User("Joe") + s = UserJSONSchema() + result = s.dumps(user) + assert result == mockjson.dumps("val") + + +def test_custom_error_message(): + class ErrorSchema(Schema): + email = fields.Email(error_messages={"invalid": "Invalid email"}) + homepage = fields.Url(error_messages={"invalid": "Bad homepage."}) + balance = fields.Decimal(error_messages={"invalid": "Bad balance."}) + + u = {"email": "joe.net", "homepage": "joe@example.com", "balance": "blah"} + s = ErrorSchema() + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert "Bad balance." in errors["balance"] + assert "Bad homepage." in errors["homepage"] + assert "Invalid email" in errors["email"] + + +def test_custom_unknown_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"unknown": custom_message} + name = fields.String() + + s = ErrorSchema() + u = {"name": "Joe", "age": 13} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["age"] + + +def test_custom_type_error_message(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema() + u = ["Joe"] + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_type_error_message_with_many(): + custom_message = "custom error message." + + class ErrorSchema(Schema): + error_messages = {"type": custom_message} + name = fields.String() + + s = ErrorSchema(many=True) + u = {"name": "Joe"} + with pytest.raises(ValidationError) as excinfo: + s.load(u) + errors = excinfo.value.messages + assert custom_message in errors["_schema"] + + +def test_custom_error_messages_with_inheritance(): + parent_type_message = "parent type error message." + parent_unknown_message = "parent unknown error message." + child_type_message = "child type error message." + + class ParentSchema(Schema): + error_messages = { + "type": parent_type_message, + "unknown": parent_unknown_message, + } + name = fields.String() + + class ChildSchema(ParentSchema): + error_messages = {"type": child_type_message} + + unknown_user = {"name": "Eleven", "age": 12} + type_user = 11 + + parent_schema = ParentSchema() + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + parent_schema.load(type_user) + assert parent_type_message in excinfo.value.messages["_schema"] + + child_schema = ChildSchema() + with pytest.raises(ValidationError) as excinfo: + child_schema.load(unknown_user) + assert parent_unknown_message in excinfo.value.messages["age"] + with pytest.raises(ValidationError) as excinfo: + child_schema.load(type_user) + assert child_type_message in excinfo.value.messages["_schema"] + + +def test_load_errors_with_many(): + class ErrorSchema(Schema): + email = fields.Email() + + data = [ + {"email": "bademail"}, + {"email": "goo@email.com"}, + {"email": "anotherbademail"}, + ] + + with pytest.raises(ValidationError) as excinfo: + ErrorSchema(many=True).load(data) + errors = excinfo.value.messages + assert 0 in errors + assert 2 in errors + assert "Not a valid email address." in errors[0]["email"][0] + assert "Not a valid email address." in errors[2]["email"][0] + + +def test_error_raised_if_fields_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = "name" + + +def test_error_raised_if_additional_option_is_not_list(): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + additional = "email" + + +def test_nested_custom_set_in_exclude_reusing_schema(): + class CustomSet: + # This custom set is to allow the obj check in BaseSchema.__filter_fields + # to pass, since it'll be a valid instance, and this class overrides + # getitem method to allow the hasattr check to pass too, which will try + # to access the first obj index and will simulate a IndexError throwing. + # e.g. SqlAlchemy.Query is a valid use case for this 'obj'. + + def __getitem__(self, item): + return [][item] + + class ChildSchema(Schema): + foo = fields.Field(required=True) + bar = fields.Field() + + class Meta: + only = ("bar",) + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, many=True, exclude=("foo",)) + + sch = ParentSchema() + obj = dict(child=CustomSet()) + sch.dumps(obj) + data = dict(child=[{"bar": 1}]) + sch.load(data, partial=True) + + +def test_nested_only(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(only=("blubb.foo", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_only_empty_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("bar",)) + + sch = ParentSchema(only=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" not in child + assert "baz" not in child + + +def test_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(exclude=("bli", "blubb.baz")) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("baz",)) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_and_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema(only=("bla", "blubb.foo", "blubb.bar"), exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_only_then_exclude_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, only=("foo", "bar")) + + sch = ParentSchema(exclude=("blubb.foo",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_then_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema, exclude=("foo",)) + + sch = ParentSchema(only=("blubb.bar",)) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + + +def test_nested_exclude_and_only_inheritance(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + ban = fields.Field() + fuu = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "bar", "baz", "ban"), exclude=("foo",) + ) + + sch = ParentSchema( + only=("blubb.foo", "blubb.bar", "blubb.baz"), exclude=("blubb.baz",) + ) + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + result = sch.dump(data) + assert "bla" not in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" not in child + assert "ban" not in child + assert "fuu" not in child + + +# https://github.com/marshmallow-code/marshmallow/issues/1160 +def test_nested_instance_many(): + class BookSchema(Schema): + id = fields.Int() + title = fields.String() + + class UserSchema(Schema): + id = fields.Int() + name = fields.String() + books = fields.Nested(BookSchema(many=True)) + + books = [{"id": 1, "title": "First book"}, {"id": 2, "title": "Second book"}] + user = {"id": 1, "name": "Peter", "books": books} + + user_dump = UserSchema().dump(user) + assert user_dump["books"] == books + + user_load = UserSchema().load(user_dump) + assert user_load == user + + +def test_nested_instance_only(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), only=("last",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_nested_instance_exclude(): + class ArtistSchema(Schema): + first = fields.Str() + last = fields.Str() + + class AlbumSchema(Schema): + title = fields.Str() + artist = fields.Nested(ArtistSchema(), exclude=("first",)) + + schema = AlbumSchema() + album = {"title": "Hunky Dory", "artist": {"last": "Bowie"}} + loaded = schema.load(album) + assert loaded == album + full_album = {"title": "Hunky Dory", "artist": {"first": "David", "last": "Bowie"}} + assert schema.dump(full_album) == album + + +def test_meta_nested_exclude(): + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + class Meta: + exclude = ("blubb.foo",) + + data = dict(bla=1, bli=2, blubb=dict(foo=42, bar=24, baz=242)) + + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + # Test fields with dot notations in Meta.exclude on multiple instantiations + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1212 + sch = ParentSchema() + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" in result + child = result["blubb"] + assert "foo" not in child + assert "bar" in child + assert "baz" in child + + +def test_nested_custom_set_not_implementing_getitem(): + # This test checks that marshmallow can serialize implementations of + # :mod:`collections.abc.MutableSequence`, with ``__getitem__`` arguments + # that are not integers. + + class ListLikeParent: + """ + Implements a list-like object that can get children using a + non-integer key + """ + + def __init__(self, required_key, child): + """ + :param required_key: The key to use in ``__getitem__`` in order + to successfully get the ``child`` + :param child: The return value of the ``child`` if + ``__getitem__`` succeeds + """ + self.children = {required_key: child} + + class Child: + """ + Implements an object with some attribute + """ + + def __init__(self, attribute): + """ + :param str attribute: The attribute to initialize + """ + self.attribute = attribute + + class ChildSchema(Schema): + """ + The marshmallow schema for the child + """ + + attribute = fields.Str() + + class ParentSchema(Schema): + """ + The schema for the parent + """ + + children = fields.Nested(ChildSchema, many=True) + + attribute = "Foo" + required_key = "key" + child = Child(attribute) + + parent = ListLikeParent(required_key, child) + + ParentSchema().dump(parent) + + +def test_deeply_nested_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested(ChildSchema) + + sch = ParentSchema( + only=("bla", "blubb.foo", "blubb.flubb.goo", "blubb.flubb.gah"), + exclude=("blubb.flubb.goo",), + ) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_nested_lambda(): + class ChildSchema(Schema): + id = fields.Str() + name = fields.Str() + parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) + siblings = fields.List(fields.Nested(lambda: ChildSchema(only=("id", "name")))) + + class ParentSchema(Schema): + id = fields.Str() + spouse = fields.Nested(lambda: ParentSchema(only=("id",))) + children = fields.List( + fields.Nested(lambda: ChildSchema(only=("id", "parent", "siblings"))) + ) + + sch = ParentSchema() + data_to_load = { + "id": "p1", + "spouse": {"id": "p2"}, + "children": [{"id": "c1", "siblings": [{"id": "c2", "name": "sis"}]}], + } + loaded = sch.load(data_to_load) + assert loaded == data_to_load + + data_to_dump = dict( + id="p2", + spouse=dict(id="p2"), + children=[ + dict( + id="c1", + name="bar", + parent=dict(id="p2"), + siblings=[dict(id="c2", name="sis")], + ) + ], + ) + dumped = sch.dump(data_to_dump) + assert dumped == { + "id": "p2", + "spouse": {"id": "p2"}, + "children": [ + { + "id": "c1", + "parent": {"id": "p2"}, + "siblings": [{"id": "c2", "name": "sis"}], + } + ], + } + + +@pytest.mark.parametrize("data_key", ("f1", "f5", None)) +def test_data_key_collision(data_key): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(data_key=data_key) + f3 = fields.Field(data_key="f5") + f4 = fields.Field(data_key="f1", load_only=True) + + if data_key is None: + MySchema() + else: + with pytest.raises(ValueError, match=data_key): + MySchema() + + +@pytest.mark.parametrize("attribute", ("f1", "f5", None)) +def test_attribute_collision(attribute): + class MySchema(Schema): + f1 = fields.Field() + f2 = fields.Field(attribute=attribute) + f3 = fields.Field(attribute="f5") + f4 = fields.Field(attribute="f1", dump_only=True) + + if attribute is None: + MySchema() + else: + with pytest.raises(ValueError, match=attribute): + MySchema() + + +class TestDeeplyNestedLoadOnly: + @pytest.fixture() + def schema(self): + class GrandChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + grand_child = fields.Nested(GrandChildSchema, unknown=EXCLUDE) + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.Nested(ChildSchema, unknown=EXCLUDE) + + return ParentSchema( + dump_only=( + "str_dump_only", + "child.str_dump_only", + "child.grand_child.str_dump_only", + ), + load_only=( + "str_load_only", + "child.str_load_only", + "child.grand_child.str_load_only", + ), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + grand_child=dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ), + ), + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_load_only" not in grand_child + assert "str_dump_only" in grand_child + assert "str_regular" in grand_child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + grand_child = child["grand_child"] + assert "str_dump_only" not in grand_child + assert "str_load_only" in grand_child + assert "str_regular" in grand_child + + +class TestDeeplyNestedListLoadOnly: + @pytest.fixture() + def schema(self): + class ChildSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + class ParentSchema(Schema): + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + child = fields.List(fields.Nested(ChildSchema, unknown=EXCLUDE)) + + return ParentSchema( + dump_only=("str_dump_only", "child.str_dump_only"), + load_only=("str_load_only", "child.str_load_only"), + ) + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + child=[ + dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + ], + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_load_only" not in child + assert "str_dump_only" in child + assert "str_regular" in child + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + child = result["child"][0] + assert "str_dump_only" not in child + assert "str_load_only" in child + assert "str_regular" in child + + +def test_nested_constructor_only_and_exclude(): + class GrandChildSchema(Schema): + goo = fields.Field() + gah = fields.Field() + bah = fields.Field() + + class ChildSchema(Schema): + foo = fields.Field() + bar = fields.Field() + flubb = fields.Nested(GrandChildSchema) + + class ParentSchema(Schema): + bla = fields.Field() + bli = fields.Field() + blubb = fields.Nested( + ChildSchema, only=("foo", "flubb.goo", "flubb.gah"), exclude=("flubb.goo",) + ) + + sch = ParentSchema(only=("bla", "blubb")) + data = dict(bla=1, bli=2, blubb=dict(foo=3, bar=4, flubb=dict(goo=5, gah=6, bah=7))) + result = sch.dump(data) + assert "bla" in result + assert "blubb" in result + assert "bli" not in result + child = result["blubb"] + assert "foo" in child + assert "flubb" in child + assert "bar" not in child + grand_child = child["flubb"] + assert "gah" in grand_child + assert "goo" not in grand_child + assert "bah" not in grand_child + + +def test_only_and_exclude(): + class MySchema(Schema): + foo = fields.Field() + bar = fields.Field() + baz = fields.Field() + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + sch = MySchema(only=("bar", "baz"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "baz" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_fields(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + fields = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foo", "par"), exclude=("ban",)) + + assert "foo" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + sch = MySchema(only=("foo", "bar"), exclude=("bar",)) + data = dict(foo=42, bar=24, baz=242) + result = sch.dump(data) + assert "foo" in result + assert "bar" not in result + + +def test_invalid_only_and_exclude_with_additional(): + class MySchema(Schema): + foo = fields.Field() + + class Meta: + additional = ("bar", "baz") + + with pytest.raises(ValueError) as excinfo: + MySchema(only=("foop", "par"), exclude=("ban",)) + + assert "foop" in str(excinfo.value) + assert "par" in str(excinfo.value) + assert "ban" in str(excinfo.value) + + +def test_exclude_invalid_attribute(): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(ValueError, match="'bar'"): + MySchema(exclude=("bar",)) + + +def test_only_bounded_by_fields(): + class MySchema(Schema): + class Meta: + fields = ("foo",) + + with pytest.raises(ValueError, match="'baz'"): + MySchema(only=("baz",)) + + +def test_only_bounded_by_additional(): + class MySchema(Schema): + class Meta: + additional = ("b",) + + with pytest.raises(ValueError): + MySchema(only=("c",)).dump({"c": 3}) + + +def test_only_empty(): + class MySchema(Schema): + foo = fields.Field() + + sch = MySchema(only=()) + assert "foo" not in sch.dump({"foo": "bar"}) + + +@pytest.mark.parametrize("param", ("only", "exclude")) +def test_only_and_exclude_as_string(param): + class MySchema(Schema): + foo = fields.Field() + + with pytest.raises(StringNotCollectionError): + MySchema(**{param: "foo"}) + + +def test_nested_with_sets(): + class Inner(Schema): + foo = fields.Field() + + class Outer(Schema): + inners = fields.Nested(Inner, many=True) + + sch = Outer() + + DataClass = namedtuple("DataClass", ["foo"]) + data = dict(inners={DataClass(42), DataClass(2)}) + result = sch.dump(data) + assert len(result["inners"]) == 2 + + +def test_meta_serializer_fields(): + u = User("John", age=42.3, email="john@example.com", homepage="http://john.com") + result = UserMetaSchema().dump(u) + assert result["name"] == u.name + assert result["balance"] == decimal.Decimal("100.00") + assert result["uppername"] == "JOHN" + assert result["is_old"] is False + assert result["created"] == utils.isoformat(u.created) + assert result["finger_count"] == 10 + assert result["various_data"] == dict(u.various_data) + + +def test_meta_fields_mapping(user): + s = UserMetaSchema() + s.dump(user) # need to call dump to update fields + assert type(s.fields["balance"]) is fields.Decimal + # Inferred fields + assert type(s.fields["name"]._field_cache[fields.String]) is fields.String + assert type(s.fields["created"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["updated"]._field_cache[fields.DateTime]) is fields.DateTime + assert type(s.fields["age"]._field_cache[fields.Float]) is fields.Float + assert type(s.fields["registered"]._field_cache[fields.Boolean]) is fields.Boolean + assert type(s.fields["sex_choices"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["hair_colors"]._field_cache[fields.Raw]) is fields.Raw + assert type(s.fields["finger_count"]._field_cache[fields.Integer]) is fields.Integer + assert type(s.fields["uid"]._field_cache[fields.UUID]) is fields.UUID + assert type(s.fields["time_registered"]._field_cache[fields.Time]) is fields.Time + assert type(s.fields["birthdate"]._field_cache[fields.Date]) is fields.Date + assert ( + type(s.fields["since_created"]._field_cache[fields.TimeDelta]) + is fields.TimeDelta + ) + + +def test_meta_field_not_on_obj_raises_attribute_error(user): + class BadUserSchema(Schema): + class Meta: + fields = ("name",) + exclude = ("notfound",) + + with pytest.raises(ValueError, match="'notfound'"): + BadUserSchema().dump(user) + + +def test_exclude_fields(user): + s = UserExcludeSchema().dump(user) + assert "created" not in s + assert "updated" not in s + assert "name" in s + + +def test_fields_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadFields(Schema): + class Meta: + fields = "name" + + +def test_exclude_option_must_be_list_or_tuple(): + with pytest.raises(ValueError): + + class BadExclude(Schema): + class Meta: + exclude = "name" + + +def test_datetimeformat_option(user): + meta_fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateTimeFormatSchema(Schema): + updated = fields.DateTime(field_fmt) + + class Meta: + fields = ("created", "updated") + datetimeformat = meta_fmt + + serialized = DateTimeFormatSchema().dump(user) + assert serialized["created"] == user.created.strftime(meta_fmt) + assert serialized["updated"] == user.updated.strftime(field_fmt) + + +def test_dateformat_option(user): + fmt = "%Y-%m" + field_fmt = "%m-%d" + + class DateFormatSchema(Schema): + birthdate = fields.Date(field_fmt) + + class Meta: + fields = ("birthdate", "activation_date") + dateformat = fmt + + serialized = DateFormatSchema().dump(user) + assert serialized["birthdate"] == user.birthdate.strftime(field_fmt) + assert serialized["activation_date"] == user.activation_date.strftime(fmt) + + +def test_timeformat_option(user): + fmt = "%H:%M:%S" + field_fmt = "%H:%M" + + class TimeFormatSchema(Schema): + birthtime = fields.Time(field_fmt) + + class Meta: + fields = ("birthtime", "time_registered") + timeformat = fmt + + serialized = TimeFormatSchema().dump(user) + assert serialized["birthtime"] == user.birthtime.strftime(field_fmt) + assert serialized["time_registered"] == user.time_registered.strftime(fmt) + + +def test_default_dateformat(user): + class DateFormatSchema(Schema): + updated = fields.DateTime(format="%m-%d") + + class Meta: + fields = ("created", "updated") + + serialized = DateFormatSchema().dump(user) + assert serialized["created"] == utils.isoformat(user.created) + assert serialized["updated"] == user.updated.strftime("%m-%d") + + +def test_inherit_meta(user): + class InheritedMetaSchema(UserMetaSchema): + pass + + result = InheritedMetaSchema().dump(user) + expected = UserMetaSchema().dump(user) + assert result == expected + + +def test_inherit_meta_override(): + class Parent(Schema): + class Meta: + fields = ("name", "email") + dump_only = ("name",) + + class Child(Schema): + class Meta(Parent.Meta): + dump_only = ("name", "email") + + child = Child() + assert child.opts.fields == ("name", "email") + assert child.opts.dump_only == ("name", "email") + + +def test_additional(user): + s = UserAdditionalSchema().dump(user) + assert s["lowername"] == user.name.lower() + assert s["name"] == user.name + + +def test_cant_set_both_additional_and_fields(user): + with pytest.raises(ValueError): + + class BadSchema(Schema): + name = fields.String() + + class Meta: + fields = ("name", "email") + additional = ("email", "homepage") + + +def test_serializing_none_meta(): + s = UserMetaSchema().dump(None) + assert s == {} + + +class CustomError(Exception): + pass + + +class MySchema(Schema): + name = fields.String() + email = fields.Email() + age = fields.Integer() + + def handle_error(self, errors, obj, **kwargs): + raise CustomError("Something bad happened") + + def test_load_with_custom_error_handler(self): + in_data = {"email": "invalid"} + + class MySchema3(Schema): + email = fields.Email() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema3().load(in_data) + + def test_load_with_custom_error_handler_and_partially_valid_data(self): + in_data = {"email": "invalid", "url": "http://valid.com"} + + class MySchema(Schema): + email = fields.Email() + url = fields.URL() + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "email" in error.messages + assert list(error.messages.keys()) == ["email"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates("num") + def validate_num(self, value): + if value < 0: + raise ValidationError("Must be greater than 0.") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert "num" in error.messages + assert list(error.messages.keys()) == ["num"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_custom_error_handler_with_validates_schema_decorator(self): + in_data = {"num": -1} + + class MySchema(Schema): + num = fields.Int() + + @validates_schema + def validates_schema(self, data, **kwargs): + raise ValidationError("Invalid schema!") + + def handle_error(self, error, data, **kwargs): + assert type(error) is ValidationError + assert list(error.messages.keys()) == ["_schema"] + assert data == in_data + raise CustomError("Something bad happened") + + with pytest.raises(CustomError): + MySchema().load(in_data) + + def test_validate_with_custom_error_handler(self): + with pytest.raises(CustomError): + MySchema().validate({"age": "notvalid", "email": "invalid"}) + + +class TestFieldValidation: + def test_errors_are_cleared_after_loading_collection(self): + def always_fail(val): + raise ValidationError("lol") + + class MySchema(Schema): + foo = fields.Str(validate=always_fail) + + schema = MySchema() + with pytest.raises(ValidationError) as excinfo: + schema.load([{"foo": "bar"}, {"foo": "baz"}], many=True) + errors = excinfo.value.messages + assert len(errors[0]["foo"]) == 1 + assert len(errors[1]["foo"]) == 1 + with pytest.raises(ValidationError) as excinfo: + schema.load({"foo": "bar"}) + errors = excinfo.value.messages + assert len(errors["foo"]) == 1 + + def test_raises_error_with_list(self): + def validator(val): + raise ValidationError(["err1", "err2"]) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == ["err1", "err2"] + + # https://github.com/marshmallow-code/marshmallow/issues/110 + def test_raises_error_with_dict(self): + def validator(val): + raise ValidationError({"code": "invalid_foo"}) + + class MySchema(Schema): + foo = fields.Field(validate=validator) + + s = MySchema() + errors = s.validate({"foo": 42}) + assert errors["foo"] == [{"code": "invalid_foo"}] + + def test_ignored_if_not_in_only(self): + class MySchema(Schema): + a = fields.Field() + b = fields.Field() + + @validates("a") + def validate_a(self, val): + raise ValidationError({"code": "invalid_a"}) + + @validates("b") + def validate_b(self, val): + raise ValidationError({"code": "invalid_b"}) + + s = MySchema(only=("b",)) + errors = s.validate({"b": "data"}) + assert errors == {"b": {"code": "invalid_b"}} + + +def test_schema_repr(): + class MySchema(Schema): + name = fields.String() + + ser = MySchema(many=True) + rep = repr(ser) + assert "MySchema" in rep + assert "many=True" in rep + + +class TestNestedSchema: + @pytest.fixture + def user(self): + return User(name="Monty", age=81) + + @pytest.fixture + def blog(self, user): + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog( + "Monty's blog", + user=user, + categories=["humor", "violence"], + collaborators=[col1, col2], + ) + return blog + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/64 + def test_nested_many_with_missing_attribute(self, user): + class SimpleBlogSchema(Schema): + title = fields.Str() + wat = fields.Nested(UserSchema, many=True) + + blog = Blog("Simple blog", user=user, collaborators=None) + schema = SimpleBlogSchema() + result = schema.dump(blog) + assert "wat" not in result + + def test_nested_with_attribute_none(self): + class InnerSchema(Schema): + bar = fields.Field() + + class MySchema(Schema): + foo = fields.Nested(InnerSchema) + + class MySchema2(Schema): + foo = fields.Nested(InnerSchema) + + s = MySchema() + result = s.dump({"foo": None}) + assert result["foo"] is None + + s2 = MySchema2() + result2 = s2.dump({"foo": None}) + assert result2["foo"] is None + + def test_nested_field_does_not_validate_required(self): + class BlogRequiredSchema(Schema): + user = fields.Nested(UserSchema, required=True) + + b = Blog("Authorless blog", user=None) + BlogRequiredSchema().dump(b) + + def test_nested_none(self): + class BlogDefaultSchema(Schema): + user = fields.Nested(UserSchema, dump_default=0) + + b = Blog("Just the default blog", user=None) + data = BlogDefaultSchema().dump(b) + assert data["user"] is None + + def test_nested(self, user, blog): + blog_serializer = BlogSchema() + serialized_blog = blog_serializer.dump(blog) + user_serializer = UserSchema() + serialized_user = user_serializer.dump(user) + assert serialized_blog["user"] == serialized_user + + with pytest.raises(ValidationError, match="email"): + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + + def test_nested_many_fields(self, blog): + serialized_blog = BlogSchema().dump(blog) + expected = [UserSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_meta_many(self, blog): + serialized_blog = BlogUserMetaSchema().dump(blog) + assert len(serialized_blog["collaborators"]) == 2 + expected = [UserMetaSchema().dump(col) for col in blog.collaborators] + assert serialized_blog["collaborators"] == expected + + def test_nested_only(self, blog): + col1 = User(name="Mick", age=123, id_="abc") + col2 = User(name="Keith", age=456, id_="def") + blog.collaborators = [col1, col2] + serialized_blog = BlogOnlySchema().dump(blog) + assert serialized_blog["collaborators"] == [{"id": col1.id}, {"id": col2.id}] + + def test_exclude(self, blog): + serialized = BlogSchemaExclude().dump(blog) + assert "uppername" not in serialized["user"].keys() + + def test_list_field(self, blog): + serialized = BlogSchema().dump(blog) + assert serialized["categories"] == ["humor", "violence"] + + def test_nested_load_many(self): + in_data = { + "title": "Shine A Light", + "collaborators": [ + {"name": "Mick", "email": "mick@stones.com"}, + {"name": "Keith", "email": "keith@stones.com"}, + ], + } + data = BlogSchema().load(in_data) + collabs = data["collaborators"] + assert len(collabs) == 2 + assert all(type(each) is User for each in collabs) + assert collabs[0].name == in_data["collaborators"][0]["name"] + + def test_nested_errors(self): + with pytest.raises(ValidationError) as excinfo: + BlogSchema().load( + {"title": "Monty's blog", "user": {"name": "Monty", "email": "foo"}} + ) + errors = excinfo.value.messages + assert "email" in errors["user"] + assert len(errors["user"]["email"]) == 1 + assert "Not a valid email address." in errors["user"]["email"][0] + # No problems with collaborators + assert "collaborators" not in errors + + def test_nested_method_field(self, blog): + data = BlogSchema().dump(blog) + assert data["user"]["is_old"] + assert data["collaborators"][0]["is_old"] + + def test_nested_function_field(self, blog, user): + data = BlogSchema().dump(blog) + assert data["user"]["lowername"] == user.name.lower() + expected = blog.collaborators[0].name.lower() + assert data["collaborators"][0]["lowername"] == expected + + def test_serializer_meta_with_nested_fields(self, blog, user): + data = BlogSchemaMeta().dump(blog) + assert data["title"] == blog.title + assert data["user"] == UserSchema().dump(user) + assert data["collaborators"] == [ + UserSchema().dump(c) for c in blog.collaborators + ] + assert data["categories"] == blog.categories + + def test_serializer_with_nested_meta_fields(self, blog): + # Schema has user = fields.Nested(UserMetaSerializer) + s = BlogUserMetaSchema().dump(blog) + assert s["user"] == UserMetaSchema().dump(blog.user) + + def test_nested_fields_must_be_passed_a_serializer(self, blog): + class BadNestedFieldSchema(BlogSchema): + user = fields.Nested(fields.String) + + with pytest.raises(ValueError): + BadNestedFieldSchema().dump(blog) + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/188 + def test_invalid_type_passed_to_nested_field(self): + class InnerSchema(Schema): + foo = fields.Field() + + class MySchema(Schema): + inner = fields.Nested(InnerSchema, many=True) + + sch = MySchema() + + sch.load({"inner": [{"foo": 42}]}) + + with pytest.raises(ValidationError) as excinfo: + sch.load({"inner": "invalid"}) + errors = excinfo.value.messages + assert "inner" in errors + assert errors["inner"] == ["Invalid type."] + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema) + + schema = OuterSchema() + with pytest.raises(ValidationError) as excinfo: + schema.load({"inner": 1}) + errors = excinfo.value.messages + assert errors["inner"]["_schema"] == ["Invalid input type."] + + # regression test for https://github.com/marshmallow-code/marshmallow/issues/298 + def test_all_errors_on_many_nested_field_with_validates_decorator(self): + class Inner(Schema): + req = fields.Field(required=True) + + class Outer(Schema): + inner = fields.Nested(Inner, many=True) + + @validates("inner") + def validates_inner(self, data): + raise ValidationError("not a chance") + + outer = Outer() + with pytest.raises(ValidationError) as excinfo: + outer.load({"inner": [{}]}) + errors = excinfo.value.messages + assert "inner" in errors + assert "_schema" in errors["inner"] + + @pytest.mark.parametrize("unknown", (None, RAISE, INCLUDE, EXCLUDE)) + def test_nested_unknown_validation(self, unknown): + class ChildSchema(Schema): + num = fields.Int() + + class ParentSchema(Schema): + child = fields.Nested(ChildSchema, unknown=unknown) + + data = {"child": {"num": 1, "extra": 1}} + if unknown is None or unknown == RAISE: + with pytest.raises(ValidationError) as exc: + ParentSchema().load(data) + assert exc.messages == {"child": {"extra": ["Unknown field."]}} + else: + output = { + INCLUDE: {"child": {"num": 1, "extra": 1}}, + EXCLUDE: {"child": {"num": 1}}, + }[unknown] + assert ParentSchema().load(data) == output + + +class TestPluckSchema: + @pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()]) + def test_pluck(self, user_schema, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(user_schema, "name") + collaborators = fields.Pluck(user_schema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + def test_pluck_none(self, blog): + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + col1 = User(name="Mick", age=123) + col2 = User(name="Keith", age=456) + blog = Blog(title="Unowned Blog", user=None, collaborators=[col1, col2]) + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/800 + def test_pluck_with_data_key(self, blog): + class UserSchema(Schema): + name = fields.String(data_key="username") + age = fields.Int() + + class FlatBlogSchema(Schema): + user = fields.Pluck(UserSchema, "name") + collaborators = fields.Pluck(UserSchema, "name", many=True) + + s = FlatBlogSchema() + data = s.dump(blog) + assert data["user"] == blog.user.name + for i, name in enumerate(data["collaborators"]): + assert name == blog.collaborators[i].name + assert s.load(data) == { + "user": {"name": "Monty"}, + "collaborators": [{"name": "Mick"}, {"name": "Keith"}], + } + + +class TestSelfReference: + @pytest.fixture + def employer(self): + return User(name="Joe", age=59) + + @pytest.fixture + def user(self, employer): + return User(name="Tom", employer=employer, age=28) + + def test_nesting_schema_by_passing_lambda(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested( + lambda: SelfReferencingSchema(exclude=("employer",)) + ) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_by_passing_class_name(self, user, employer): + class SelfReferencingSchema(Schema): + name = fields.Str() + age = fields.Int() + employer = fields.Nested("SelfReferencingSchema", exclude=("employer",)) + + data = SelfReferencingSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_schema_self_string(self, user, employer): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfSchema(Schema): + name = fields.String() + age = fields.Integer() + employer = fields.Nested("self", exclude=("employer",)) + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nesting_within_itself_meta(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(exclude=("employer",))) + + class Meta: + additional = ("name", "age") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["age"] == user.age + assert data["employer"]["name"] == employer.name + assert data["employer"]["age"] == employer.age + + def test_nested_self_with_only_param(self, user, employer): + class SelfSchema(Schema): + employer = fields.Nested(lambda: SelfSchema(only=("name",))) + + class Meta: + fields = ("name", "employer") + + data = SelfSchema().dump(user) + assert data["name"] == user.name + assert data["employer"]["name"] == employer.name + assert "age" not in data["employer"] + + def test_multiple_pluck_self_lambda(self, user): + class MultipleSelfSchema(Schema): + emp = fields.Pluck( + lambda: MultipleSelfSchema(), "name", attribute="employer" + ) + rels = fields.Pluck( + lambda: MultipleSelfSchema(), "name", many=True, attribute="relatives" + ) + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_multiple_pluck_self_string(self, user): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class MultipleSelfSchema(Schema): + emp = fields.Pluck("self", "name", attribute="employer") + rels = fields.Pluck("self", "name", many=True, attribute="relatives") + + class Meta: + fields = ("name", "emp", "rels") + + schema = MultipleSelfSchema() + user.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = schema.dump(user) + assert len(data["rels"]) == len(user.relatives) + relative = data["rels"][0] + assert relative == user.relatives[0].name + + def test_nested_self_many_lambda(self): + class SelfManySchema(Schema): + relatives = fields.Nested(lambda: SelfManySchema(), many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_many_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfManySchema(Schema): + relatives = fields.Nested("self", many=True) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfManySchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list(self): + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested(lambda: SelfListSchema())) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + def test_nested_self_list_string(self): + with pytest.warns( + DeprecationWarning, match="Passing 'self' to `Nested` is deprecated" + ): + + class SelfListSchema(Schema): + relatives = fields.List(fields.Nested("self")) + + class Meta: + additional = ("name", "age") + + person = User(name="Foo") + person.relatives = [User(name="Bar", age=12), User(name="Baz", age=34)] + data = SelfListSchema().dump(person) + assert data["name"] == person.name + assert len(data["relatives"]) == len(person.relatives) + assert data["relatives"][0]["name"] == person.relatives[0].name + assert data["relatives"][0]["age"] == person.relatives[0].age + + +class RequiredUserSchema(Schema): + name = fields.Field(required=True) + + +def test_serialization_with_required_field(): + user = User(name=None) + RequiredUserSchema().dump(user) + + +def test_deserialization_with_required_field(): + in_data = {} + with pytest.raises(ValidationError) as excinfo: + RequiredUserSchema().load(in_data) + data, errors = excinfo.value.valid_data, excinfo.value.messages + assert "name" in errors + assert "Missing data for required field." in errors["name"] + # field value should also not be in output data + assert "name" not in data + + +def test_deserialization_with_required_field_and_custom_validator(): + class ValidatingSchema(Schema): + color = fields.String( + required=True, + validate=lambda x: x.lower() == "red" or x.lower() == "blue", + error_messages={"validator_failed": "Color must be red or blue"}, + ) + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"name": "foo"}) + errors = excinfo.value.messages + assert errors + assert "color" in errors + assert "Missing data for required field." in errors["color"] + + with pytest.raises(ValidationError) as excinfo: + ValidatingSchema().load({"color": "green"}) + errors = excinfo.value.messages + assert "color" in errors + assert "Color must be red or blue" in errors["color"] + + +class UserContextSchema(Schema): + is_owner = fields.Method("get_is_owner") + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + def get_is_owner(self, user): + return self.context["blog"].user.name == user.name + + +class TestContext: + def test_context_method(self): + owner = User("Joe") + blog = Blog(title="Joe Blog", user=owner) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(owner) + assert data["is_owner"] is True + nonowner = User("Fred") + data = serializer.dump(nonowner) + assert data["is_owner"] is False + + def test_context_method_function(self): + owner = User("Fred") + blog = Blog("Killer Queen", user=owner) + collab = User("Brian") + blog.collaborators.append(collab) + context = {"blog": blog} + serializer = UserContextSchema() + serializer.context = context + data = serializer.dump(collab) + assert data["is_collab"] is True + noncollab = User("Foo") + data = serializer.dump(noncollab) + assert data["is_collab"] is False + + def test_function_field_raises_error_when_context_not_available(self): + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(lambda user, ctx: user in ctx["blog"]) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + msg = "No context available for Function field {!r}".format("is_collab") + with pytest.raises(ValidationError, match=msg): + serializer.dump(owner) + + def test_function_field_handles_bound_serializer(self): + class SerializeA: + def __call__(self, value): + return "value" + + serialize = SerializeA() + + # only has a function field + class UserFunctionContextSchema(Schema): + is_collab = fields.Function(serialize) + + owner = User("Joe") + serializer = UserFunctionContextSchema() + # no context + serializer.context = None + data = serializer.dump(owner) + assert data["is_collab"] == "value" + + def test_fields_context(self): + class CSchema(Schema): + name = fields.String() + + ser = CSchema() + ser.context["foo"] = 42 + + assert ser.fields["name"].context == {"foo": 42} + + def test_nested_fields_inherit_context(self): + class InnerSchema(Schema): + likes_bikes = fields.Function(lambda obj, ctx: "bikes" in ctx["info"]) + + class CSchema(Schema): + inner = fields.Nested(InnerSchema) + + ser = CSchema() + ser.context["info"] = "i like bikes" + obj = {"inner": {}} + result = ser.dump(obj) + assert result["inner"]["likes_bikes"] is True + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_list_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.List(fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": [{"foo": 42}]}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/820 + def test_nested_dict_fields_inherit_context(self): + class InnerSchema(Schema): + foo = fields.Field() + + @validates("foo") + def validate_foo(self, value): + if "foo_context" not in self.context: + raise ValidationError("Missing context") + + class OuterSchema(Schema): + bars = fields.Dict(values=fields.Nested(InnerSchema())) + + inner = InnerSchema() + inner.context["foo_context"] = "foo" + assert inner.load({"foo": 42}) + + outer = OuterSchema() + outer.context["foo_context"] = "foo" + assert outer.load({"bars": {"test": {"foo": 42}}}) + + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1404 + def test_nested_field_with_unpicklable_object_in_context(self): + class Unpicklable: + def __deepcopy__(self, _): + raise NotImplementedError + + class InnerSchema(Schema): + foo = fields.Field() + + class OuterSchema(Schema): + inner = fields.Nested(InnerSchema(context={"unp": Unpicklable()})) + + outer = OuterSchema() + obj = {"inner": {"foo": 42}} + assert outer.dump(obj) + + +def test_serializer_can_specify_nested_object_as_attribute(blog): + class BlogUsernameSchema(Schema): + author_name = fields.String(attribute="user.name") + + ser = BlogUsernameSchema() + result = ser.dump(blog) + assert result["author_name"] == blog.user.name + + +class TestFieldInheritance: + def test_inherit_fields_from_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + assert SerializerB._declared_fields == expected + + def test_inherit_fields_from_non_schema_subclass(self): + expected = { + "field_a": fields.Number(), + "field_b": fields.Number(), + } + + class PlainBaseClass: + field_a = expected["field_a"] + + class SerializerB1(Schema, PlainBaseClass): + field_b = expected["field_b"] + + class SerializerB2(PlainBaseClass, Schema): + field_b = expected["field_b"] + + assert SerializerB1._declared_fields == expected + assert SerializerB2._declared_fields == expected + + def test_inheritance_follows_mro(self): + expected = { + "field_a": fields.String(), + "field_b": fields.String(), + "field_c": fields.String(), + "field_d": fields.String(), + } + # Diamond inheritance graph + # MRO: D -> B -> C -> A + + class SerializerA(Schema): + field_a = expected["field_a"] + + class SerializerB(SerializerA): + field_b = expected["field_b"] + + class SerializerC(SerializerA): + field_c = expected["field_c"] + + class SerializerD(SerializerB, SerializerC): + field_d = expected["field_d"] + + assert SerializerD._declared_fields == expected + + +def get_from_dict(schema, obj, key, default=None): + return obj.get("_" + key, default) + + +class TestGetAttribute: + def test_get_attribute_is_used(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dict = {"_name": "joe", "_email": "joe@shmoe.com"} + schema = UserDictSchema() + result = schema.dump(user_dict) + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + user = User(name="joe", email="joe@shmoe.com") + with pytest.raises(AttributeError): + schema.dump(user) + + def test_get_attribute_with_many(self): + class UserDictSchema(Schema): + name = fields.Str() + email = fields.Email() + + def get_attribute(self, obj, attr, default): + return get_from_dict(self, obj, attr, default) + + user_dicts = [ + {"_name": "joe", "_email": "joe@shmoe.com"}, + {"_name": "jane", "_email": "jane@shmane.com"}, + ] + schema = UserDictSchema(many=True) + results = schema.dump(user_dicts) + for result, user_dict in zip(results, user_dicts): + assert result["name"] == user_dict["_name"] + assert result["email"] == user_dict["_email"] + # can't serialize User object + users = [ + User(name="joe", email="joe@shmoe.com"), + User(name="jane", email="jane@shmane.com"), + ] + with pytest.raises(AttributeError): + schema.dump(users) + + +class TestRequiredFields: + class StringSchema(Schema): + required_field = fields.Str(required=True) + allow_none_field = fields.Str(allow_none=True) + allow_none_required_field = fields.Str(required=True, allow_none=True) + + @pytest.fixture() + def string_schema(self): + return self.StringSchema() + + @pytest.fixture() + def data(self): + return dict( + required_field="foo", + allow_none_field="bar", + allow_none_required_field="one", + ) + + def test_required_string_field_missing(self, string_schema, data): + del data["required_field"] + errors = string_schema.validate(data) + assert errors["required_field"] == ["Missing data for required field."] + + def test_required_string_field_failure(self, string_schema, data): + data["required_field"] = None + errors = string_schema.validate(data) + assert errors["required_field"] == ["Field may not be null."] + + def test_allow_none_param(self, string_schema, data): + data["allow_none_field"] = None + errors = string_schema.validate(data) + assert errors == {} + + data["allow_none_required_field"] = None + string_schema.validate(data) + + del data["allow_none_required_field"] + errors = string_schema.validate(data) + assert "allow_none_required_field" in errors + + def test_allow_none_custom_message(self, data): + class MySchema(Schema): + allow_none_field = fields.Field( + allow_none=False, error_messages={"null": ""} + ) + + schema = MySchema() + errors = schema.validate({"allow_none_field": None}) + assert errors["allow_none_field"][0] == "" + + +class TestDefaults: + class MySchema(Schema): + int_no_default = fields.Int(allow_none=True) + str_no_default = fields.Str(allow_none=True) + list_no_default = fields.List(fields.Str, allow_none=True) + nested_no_default = fields.Nested(UserSchema, many=True, allow_none=True) + + int_with_default = fields.Int(allow_none=True, dump_default=42) + str_with_default = fields.Str(allow_none=True, dump_default="foo") + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + int_no_default=None, + str_no_default=None, + list_no_default=None, + nested_no_default=None, + int_with_default=None, + str_with_default=None, + ) + + def test_missing_inputs_are_excluded_from_dump_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.dump(d) + # the missing key is not in the serialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + def test_none_is_serialized_to_none(self, schema, data): + errors = schema.validate(data) + assert errors == {} + result = schema.dump(data) + for key in data.keys(): + msg = f"result[{key!r}] should be None" + assert result[key] is None, msg + + def test_default_and_value_missing(self, schema, data): + del data["int_with_default"] + del data["str_with_default"] + result = schema.dump(data) + assert result["int_with_default"] == 42 + assert result["str_with_default"] == "foo" + + def test_loading_none(self, schema, data): + result = schema.load(data) + for key in data.keys(): + assert result[key] is None + + def test_missing_inputs_are_excluded_from_load_output(self, schema, data): + for key in [ + "int_no_default", + "str_no_default", + "list_no_default", + "nested_no_default", + ]: + d = data.copy() + del d[key] + result = schema.load(d) + # the missing key is not in the deserialized result + assert key not in result + # the rest of the keys are in the result + assert all(k in result for k in d.keys()) + + +class TestLoadOnly: + class MySchema(Schema): + class Meta: + load_only = ("str_load_only",) + dump_only = ("str_dump_only",) + + str_dump_only = fields.String() + str_load_only = fields.String() + str_regular = fields.String() + + @pytest.fixture() + def schema(self): + return self.MySchema() + + @pytest.fixture() + def data(self): + return dict( + str_dump_only="Dump Only", + str_load_only="Load Only", + str_regular="Regular String", + ) + + def test_load_only(self, schema, data): + result = schema.dump(data) + assert "str_load_only" not in result + assert "str_dump_only" in result + assert "str_regular" in result + + def test_dump_only(self, schema, data): + result = schema.load(data, unknown=EXCLUDE) + assert "str_dump_only" not in result + assert "str_load_only" in result + assert "str_regular" in result + + # regression test for https://github.com/marshmallow-code/marshmallow/pull/765 + def test_url_field_requre_tld_false(self): + class NoTldTestSchema(Schema): + url = fields.Url(require_tld=False, schemes=["marshmallow"]) + + schema = NoTldTestSchema() + data_with_no_top_level_domain = {"url": "marshmallow://app/discounts"} + result = schema.load(data_with_no_top_level_domain) + assert result == data_with_no_top_level_domain + + +class TestFromDict: + def test_generates_schema(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert issubclass(MySchema, Schema) + + def test_name(self): + MySchema = Schema.from_dict({"foo": fields.Str()}) + assert "GeneratedSchema" in repr(MySchema) + SchemaWithName = Schema.from_dict( + {"foo": fields.Int()}, name="MyGeneratedSchema" + ) + assert "MyGeneratedSchema" in repr(SchemaWithName) + + def test_generated_schemas_are_not_registered(self): + n_registry_entries = len(class_registry._registry) + Schema.from_dict({"foo": fields.Str()}) + Schema.from_dict({"bar": fields.Str()}, name="MyGeneratedSchema") + assert len(class_registry._registry) == n_registry_entries + with pytest.raises(RegistryError): + class_registry.get_class("GeneratedSchema") + with pytest.raises(RegistryError): + class_registry.get_class("MyGeneratedSchema") + + def test_meta_options_are_applied(self): + class OrderedSchema(Schema): + class Meta: + ordered = True + load_only = ("bar",) + + OSchema = OrderedSchema.from_dict({"foo": fields.Int(), "bar": fields.Int()}) + dumped = OSchema().dump({"foo": 42, "bar": 24}) + assert isinstance(dumped, OrderedDict) + assert "bar" not in dumped + + +def test_class_registry_returns_schema_type(): + class DefinitelyUniqueSchema(Schema): + """ + Just a schema + """ + + SchemaClass = class_registry.get_class(DefinitelyUniqueSchema.__name__) + assert SchemaClass is DefinitelyUniqueSchema + + +@pytest.mark.parametrize("usage_location", ["meta", "init", "load"]) +def test_unknown_parameter_value_is_validated(usage_location): + class MySchema(Schema): + foo = fields.String() + + with pytest.raises( + ValueError, + match="Object 'badval' is not a valid value for the 'unknown' parameter", + ): + # Meta.unknown setting gets caught at class creation time, since that's when + # metaclass __new__ runs + if usage_location == "meta": + + class SubSchema(MySchema): + class Meta: + unknown = "badval" + + # usages in init and load are caught at call time, as expected + elif usage_location == "init": + MySchema(unknown="badval") + else: + MySchema().load({"foo": "bar"}, unknown="badval") + + +@pytest.mark.parametrize("dict_cls", (dict, OrderedDict)) +def test_set_dict_class(dict_cls): + """Demonstrate how to specify dict_class as class attribute""" + + class MySchema(Schema): + dict_class = dict_cls + foo = fields.String() + + result = MySchema().dump({"foo": "bar"}) + assert result == {"foo": "bar"} + assert isinstance(result, dict_cls) diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_serialization.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..df778ce82e570540b011ce4e1013f3da5a2000c2 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_serialization.py @@ -0,0 +1,1041 @@ +"""Tests for field serialization.""" + +import datetime as dt +import decimal +import ipaddress +import itertools +import math +import uuid +from collections import OrderedDict, namedtuple + +import pytest + +from marshmallow import Schema, fields +from marshmallow import missing as missing_ +from tests.base import ALL_FIELDS, DateEnum, GenderEnum, HairColorEnum, User, central + + +class DateTimeList: + def __init__(self, dtimes): + self.dtimes = dtimes + + +class IntegerList: + def __init__(self, ints): + self.ints = ints + + +class DateTimeIntegerTuple: + def __init__(self, dtime_int): + self.dtime_int = dtime_int + + +class TestFieldSerialization: + @pytest.fixture + def user(self): + return User("Foo", email="foo@bar.com", age=42) + + @pytest.mark.parametrize( + ("value", "expected"), [(42, float(42)), (0, float(0)), (None, None)] + ) + def test_number(self, value, expected, user): + field = fields.Number() + user.age = value + assert field.serialize("age", user) == expected + + def test_number_as_string(self, user): + user.age = 42 + field = fields.Number(as_string=True) + assert field.serialize("age", user) == str(float(user.age)) + + def test_number_as_string_passed_none(self, user): + user.age = None + field = fields.Number(as_string=True, allow_none=True) + assert field.serialize("age", user) is None + + def test_function_field_passed_func(self, user): + field = fields.Function(lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + def test_function_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert field.dump_only is True + + def test_function_field_passed_deserialize_and_serialize_is_not_dump_only(self): + field = fields.Function( + serialize=lambda val: val.lower(), deserialize=lambda val: val.upper() + ) + assert field.dump_only is False + + def test_function_field_passed_serialize(self, user): + field = fields.Function(serialize=lambda obj: obj.name.upper()) + assert "FOO" == field.serialize("key", user) + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_function_field_does_not_swallow_attribute_error(self, user): + def raise_error(obj): + raise AttributeError() + + field = fields.Function(serialize=raise_error) + with pytest.raises(AttributeError): + field.serialize("key", user) + + def test_serialize_with_load_only_param(self): + class AliasingUserSerializer(Schema): + name = fields.String() + years = fields.Integer(load_only=True) + size = fields.Integer(dump_only=True, load_only=True) + nicknames = fields.List(fields.Str(), load_only=True) + + data = { + "name": "Mick", + "years": "42", + "size": "12", + "nicknames": ["Your Majesty", "Brenda"], + } + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert "years" not in result + assert "size" not in result + assert "nicknames" not in result + + def test_function_field_load_only(self): + field = fields.Function(deserialize=lambda obj: None) + assert field.load_only + + def test_function_field_passed_serialize_with_context(self, user, monkeypatch): + class Parent(Schema): + pass + + field = fields.Function( + serialize=lambda obj, context: obj.name.upper() + context["key"] + ) + field.parent = Parent(context={"key": "BAR"}) + assert "FOOBAR" == field.serialize("key", user) + + def test_function_field_passed_uncallable_object(self): + with pytest.raises(TypeError): + fields.Function("uncallable") + + def test_integer_field(self, user): + field = fields.Integer() + assert field.serialize("age", user) == 42 + + def test_integer_as_string_field(self, user): + field = fields.Integer(as_string=True) + assert field.serialize("age", user) == "42" + + def test_integer_field_default(self, user): + user.age = None + field = fields.Integer(dump_default=0) + assert field.serialize("age", user) is None + # missing + assert field.serialize("age", {}) == 0 + + def test_integer_field_default_set_to_none(self, user): + user.age = None + field = fields.Integer(dump_default=None) + assert field.serialize("age", user) is None + + def test_uuid_field(self, user): + user.uuid1 = uuid.UUID("12345678123456781234567812345678") + user.uuid2 = None + + field = fields.UUID() + assert isinstance(field.serialize("uuid1", user), str) + assert field.serialize("uuid1", user) == "12345678-1234-5678-1234-567812345678" + assert field.serialize("uuid2", user) is None + + def test_ip_address_field(self, user): + ipv4_string = "192.168.0.1" + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IP() + assert isinstance(field_compressed.serialize("ipv4", user), str) + assert field_compressed.serialize("ipv4", user) == ipv4_string + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IP(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ipv4_address_field(self, user): + ipv4_string = "192.168.0.1" + + user.ipv4 = ipaddress.ip_address(ipv4_string) + user.empty_ip = None + + field = fields.IPv4() + assert isinstance(field.serialize("ipv4", user), str) + assert field.serialize("ipv4", user) == ipv4_string + assert field.serialize("empty_ip", user) is None + + def test_ipv6_address_field(self, user): + ipv6_string = "ffff::ffff" + ipv6_exploded_string = ipaddress.ip_address("ffff::ffff").exploded + + user.ipv6 = ipaddress.ip_address(ipv6_string) + user.empty_ip = None + + field_compressed = fields.IPv6() + assert isinstance(field_compressed.serialize("ipv6", user), str) + assert field_compressed.serialize("ipv6", user) == ipv6_string + assert field_compressed.serialize("empty_ip", user) is None + + field_exploded = fields.IPv6(exploded=True) + assert isinstance(field_exploded.serialize("ipv6", user), str) + assert field_exploded.serialize("ipv6", user) == ipv6_exploded_string + + def test_ip_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPInterface() + assert isinstance(field_compressed.serialize("ipv4interface", user), str) + assert field_compressed.serialize("ipv4interface", user) == ipv4interface_string + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPInterface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_ipv4_interface_field(self, user): + ipv4interface_string = "192.168.0.1/24" + + user.ipv4interface = ipaddress.ip_interface(ipv4interface_string) + user.empty_ipinterface = None + + field = fields.IPv4Interface() + assert isinstance(field.serialize("ipv4interface", user), str) + assert field.serialize("ipv4interface", user) == ipv4interface_string + assert field.serialize("empty_ipinterface", user) is None + + def test_ipv6_interface_field(self, user): + ipv6interface_string = "ffff::ffff/128" + ipv6interface_exploded_string = ipaddress.ip_interface( + "ffff::ffff/128" + ).exploded + + user.ipv6interface = ipaddress.ip_interface(ipv6interface_string) + user.empty_ipinterface = None + + field_compressed = fields.IPv6Interface() + assert isinstance(field_compressed.serialize("ipv6interface", user), str) + assert field_compressed.serialize("ipv6interface", user) == ipv6interface_string + assert field_compressed.serialize("empty_ipinterface", user) is None + + field_exploded = fields.IPv6Interface(exploded=True) + assert isinstance(field_exploded.serialize("ipv6interface", user), str) + assert ( + field_exploded.serialize("ipv6interface", user) + == ipv6interface_exploded_string + ) + + def test_enum_field_by_symbol_serialization(self, user): + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum) + assert field.serialize("sex", user) == "male" + + def test_enum_field_by_value_true_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=True) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=True) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + + def test_enum_field_by_value_field_serialization(self, user): + user.hair_color = HairColorEnum.black + field = fields.Enum(HairColorEnum, by_value=fields.String) + assert field.serialize("hair_color", user) == "black hair" + user.sex = GenderEnum.male + field = fields.Enum(GenderEnum, by_value=fields.Integer) + assert field.serialize("sex", user) == 1 + user.some_date = DateEnum.date_1 + field = fields.Enum(DateEnum, by_value=fields.Date(format="%d/%m/%Y")) + assert field.serialize("some_date", user) == "29/02/2004" + + def test_decimal_field(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal() + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.355") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.4") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN) + assert isinstance(field.serialize("m1", user), decimal.Decimal) + assert field.serialize("m1", user) == decimal.Decimal(12) + assert isinstance(field.serialize("m2", user), decimal.Decimal) + assert field.serialize("m2", user) == decimal.Decimal("12.3") + assert isinstance(field.serialize("m3", user), decimal.Decimal) + assert field.serialize("m3", user) == decimal.Decimal(1) + assert field.serialize("m4", user) is None + + def test_decimal_field_string(self, user): + user.m1 = 12 + user.m2 = "12.355" + user.m3 = decimal.Decimal(1) + user.m4 = None + + field = fields.Decimal(as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.355" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.4" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + field = fields.Decimal(1, decimal.ROUND_DOWN, as_string=True) + assert isinstance(field.serialize("m1", user), str) + assert field.serialize("m1", user) == "12.0" + assert isinstance(field.serialize("m2", user), str) + assert field.serialize("m2", user) == "12.3" + assert isinstance(field.serialize("m3", user), str) + assert field.serialize("m3", user) == "1.0" + assert field.serialize("m4", user) is None + + def test_decimal_field_special_values(self, user): + user.m1 = "-NaN" + user.m2 = "NaN" + user.m3 = "-sNaN" + user.m4 = "sNaN" + user.m5 = "-Infinity" + user.m6 = "Infinity" + user.m7 = "-0" + + field = fields.Decimal(places=2, allow_nan=True) + + m1s = field.serialize("m1", user) + assert isinstance(m1s, decimal.Decimal) + assert m1s.is_qnan() and not m1s.is_signed() + + m2s = field.serialize("m2", user) + assert isinstance(m2s, decimal.Decimal) + assert m2s.is_qnan() and not m2s.is_signed() + + m3s = field.serialize("m3", user) + assert isinstance(m3s, decimal.Decimal) + assert m3s.is_qnan() and not m3s.is_signed() + + m4s = field.serialize("m4", user) + assert isinstance(m4s, decimal.Decimal) + assert m4s.is_qnan() and not m4s.is_signed() + + m5s = field.serialize("m5", user) + assert isinstance(m5s, decimal.Decimal) + assert m5s.is_infinite() and m5s.is_signed() + + m6s = field.serialize("m6", user) + assert isinstance(m6s, decimal.Decimal) + assert m6s.is_infinite() and not m6s.is_signed() + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + field = fields.Decimal(as_string=True, allow_nan=True) + + m2s = field.serialize("m2", user) + assert isinstance(m2s, str) + assert m2s == user.m2 + + m5s = field.serialize("m5", user) + assert isinstance(m5s, str) + assert m5s == user.m5 + + m6s = field.serialize("m6", user) + assert isinstance(m6s, str) + assert m6s == user.m6 + + def test_decimal_field_special_values_not_permitted(self, user): + user.m7 = "-0" + + field = fields.Decimal(places=2) + + m7s = field.serialize("m7", user) + assert isinstance(m7s, decimal.Decimal) + assert m7s.is_zero() and m7s.is_signed() + + def test_decimal_field_fixed_point_representation(self, user): + """ + Test we get fixed-point string representation for a Decimal number that would normally + output in engineering notation. + """ + user.m1 = "0.00000000100000000" + + field = fields.Decimal() + s = field.serialize("m1", user) + assert isinstance(s, decimal.Decimal) + assert s == decimal.Decimal("1.00000000E-9") + + field = fields.Decimal(as_string=True) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == user.m1 + + field = fields.Decimal(as_string=True, places=2) + s = field.serialize("m1", user) + assert isinstance(s, str) + assert s == "0.00" + + def test_boolean_field_serialization(self, user): + field = fields.Boolean() + + user.truthy = "non-falsy-ish" + user.falsy = "false" + user.none = None + + assert field.serialize("truthy", user) is True + assert field.serialize("falsy", user) is False + assert field.serialize("none", user) is None + + def test_email_field_serialize_none(self, user): + user.email = None + field = fields.Email() + assert field.serialize("email", user) is None + + def test_dict_field_serialize_none(self, user): + user.various_data = None + field = fields.Dict() + assert field.serialize("various_data", user) is None + + def test_dict_field_serialize(self, user): + user.various_data = {"foo": "bar"} + field = fields.Dict() + dump = field.serialize("various_data", user) + assert dump == {"foo": "bar"} + # Check dump is a distinct object + dump["foo"] = "baz" + assert user.various_data["foo"] == "bar" + + def test_dict_field_serialize_ordereddict(self, user): + user.various_data = OrderedDict([("foo", "bar"), ("bar", "baz")]) + field = fields.Dict() + assert field.serialize("various_data", user) == OrderedDict( + [("foo", "bar"), ("bar", "baz")] + ) + + def test_structured_dict_value_serialize(self, user): + user.various_data = {"foo": decimal.Decimal("1")} + field = fields.Dict(values=fields.Decimal) + assert field.serialize("various_data", user) == {"foo": 1} + + def test_structured_dict_key_serialize(self, user): + user.various_data = {1: "bar"} + field = fields.Dict(keys=fields.Str) + assert field.serialize("various_data", user) == {"1": "bar"} + + def test_structured_dict_key_value_serialize(self, user): + user.various_data = {1: decimal.Decimal("1")} + field = fields.Dict(keys=fields.Str, values=fields.Decimal) + assert field.serialize("various_data", user) == {"1": 1} + + def test_url_field_serialize_none(self, user): + user.homepage = None + field = fields.Url() + assert field.serialize("homepage", user) is None + + def test_method_field_with_method_missing(self): + class BadSerializer(Schema): + bad_field = fields.Method("invalid") + + with pytest.raises(AttributeError): + BadSerializer() + + def test_method_field_passed_serialize_only_is_dump_only(self, user): + field = fields.Method(serialize="method") + assert field.dump_only is True + assert field.load_only is False + + def test_method_field_passed_deserialize_only_is_load_only(self): + field = fields.Method(deserialize="somemethod") + assert field.load_only is True + assert field.dump_only is False + + def test_method_field_with_uncallable_attribute(self): + class BadSerializer(Schema): + foo = "not callable" + bad_field = fields.Method("foo") + + with pytest.raises(TypeError): + BadSerializer() + + # https://github.com/marshmallow-code/marshmallow/issues/395 + def test_method_field_does_not_swallow_attribute_error(self): + class MySchema(Schema): + mfield = fields.Method("raise_error") + + def raise_error(self, obj): + raise AttributeError() + + with pytest.raises(AttributeError): + MySchema().dump({}) + + def test_method_with_no_serialize_is_missing(self): + m = fields.Method() + m.parent = Schema() + + assert m.serialize("", "", "") is missing_ + + def test_serialize_with_data_key_param(self): + class DumpToSchema(Schema): + name = fields.String(data_key="NamE") + years = fields.Integer(data_key="YearS") + + data = {"name": "Richard", "years": 11} + result = DumpToSchema().dump(data) + assert result == {"NamE": "Richard", "YearS": 11} + + def test_serialize_with_data_key_as_empty_string(self): + class MySchema(Schema): + name = fields.Field(data_key="") + + schema = MySchema() + assert schema.dump({"name": "Grace"}) == {"": "Grace"} + + def test_serialize_with_attribute_and_data_key_uses_data_key(self): + class ConfusedDumpToAndAttributeSerializer(Schema): + name = fields.String(data_key="FullName") + username = fields.String(attribute="uname", data_key="UserName") + years = fields.Integer(attribute="le_wild_age", data_key="Years") + + data = {"name": "Mick", "uname": "mick_the_awesome", "le_wild_age": 999} + result = ConfusedDumpToAndAttributeSerializer().dump(data) + + assert result == { + "FullName": "Mick", + "UserName": "mick_the_awesome", + "Years": 999, + } + + @pytest.mark.parametrize("fmt", ["rfc", "rfc822"]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], + ) + def test_datetime_field_rfc822(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize( + ("fmt", "value", "expected"), + [ + ("timestamp", dt.datetime(1970, 1, 1), 0), + ("timestamp", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025, + ), + ( + "timestamp", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625, + ), + ("timestamp_ms", dt.datetime(2013, 11, 10, 0, 23, 45), 1384043025000), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=dt.timezone.utc), + 1384043025000, + ), + ( + "timestamp_ms", + dt.datetime(2013, 11, 10, 0, 23, 45, tzinfo=central), + 1384064625000, + ), + ], + ) + def test_datetime_field_timestamp(self, fmt, value, expected): + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], + ) + def test_datetime_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.DateTime() + else: + field = fields.DateTime(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_datetime_field_format(self, user): + format = "%Y-%m-%d" + field = fields.DateTime(format=format) + assert field.serialize("created", user) == user.created.strftime(format) + + def test_string_field(self): + field = fields.String() + user = User(name=b"foo") + assert field.serialize("name", user) == "foo" + field = fields.String(allow_none=True) + user.name = None + assert field.serialize("name", user) is None + + def test_string_field_default_to_empty_string(self, user): + field = fields.String(dump_default="") + assert field.serialize("notfound", {}) == "" + + def test_time_field(self, user): + field = fields.Time() + expected = user.time_registered.isoformat()[:15] + assert field.serialize("time_registered", user) == expected + + user.time_registered = None + assert field.serialize("time_registered", user) is None + + @pytest.mark.parametrize("fmt", ["iso", "iso8601", None]) + @pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.time(1, 23, 45), "01:23:45"), + (dt.time(1, 23, 45, 123000), "01:23:45.123000"), + (dt.time(1, 23, 45, 123456), "01:23:45.123456"), + ], + ) + def test_time_field_iso8601(self, fmt, value, expected): + if fmt is None: + # Test default is ISO + field = fields.Time() + else: + field = fields.Time(format=fmt) + assert field.serialize("d", {"d": value}) == expected + + def test_time_field_format(self, user): + fmt = "%H:%M:%S" + field = fields.Time(format=fmt) + assert field.serialize("birthtime", user) == user.birthtime.strftime(fmt) + + def test_date_field(self, user): + field = fields.Date() + assert field.serialize("birthdate", user) == user.birthdate.isoformat() + + user.birthdate = None + assert field.serialize("birthdate", user) is None + + def test_timedelta_field(self, user): + user.d1 = dt.timedelta(days=1, seconds=1, microseconds=1) + user.d2 = dt.timedelta(days=0, seconds=86401, microseconds=1) + user.d3 = dt.timedelta(days=0, seconds=0, microseconds=86401000001) + user.d4 = dt.timedelta(days=0, seconds=0, microseconds=0) + user.d5 = dt.timedelta(days=-1, seconds=0, microseconds=0) + user.d6 = dt.timedelta( + days=1, + seconds=1, + microseconds=1, + milliseconds=1, + minutes=1, + hours=1, + weeks=1, + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d1", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d1", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d1", user) == 86401000001 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d1", user) == 24 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d2", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d2", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d2", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d3", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d3", user) == 86401 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d3", user) == 86401000001 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d4", user) == 0 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d4", user) == 0 + + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d5", user) == -1 + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d5", user) == -86400 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d5", user) == -86400000000 + + field = fields.TimeDelta(fields.TimeDelta.WEEKS) + assert field.serialize("d6", user) == 1 + field = fields.TimeDelta(fields.TimeDelta.DAYS) + assert field.serialize("d6", user) == 7 + 1 + field = fields.TimeDelta(fields.TimeDelta.HOURS) + assert field.serialize("d6", user) == 7 * 24 + 24 + 1 + field = fields.TimeDelta(fields.TimeDelta.MINUTES) + assert field.serialize("d6", user) == 7 * 24 * 60 + 24 * 60 + 60 + 1 + d6_seconds = ( + 7 * 24 * 60 * 60 + + 24 * 60 * 60 # 1 week + + 60 * 60 # 1 day + + 60 # 1 hour + + 1 # 1 minute + ) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d6", user) == d6_seconds + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d6", user) == d6_seconds * 1000 + 1 + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS) + assert field.serialize("d6", user) == d6_seconds * 10**6 + 1000 + 1 + + user.d7 = None + assert field.serialize("d7", user) is None + + # https://github.com/marshmallow-code/marshmallow/issues/1856 + user.d8 = dt.timedelta(milliseconds=345) + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS) + assert field.serialize("d8", user) == 345 + + user.d9 = dt.timedelta(milliseconds=1999) + field = fields.TimeDelta(fields.TimeDelta.SECONDS) + assert field.serialize("d9", user) == 1 + + user.d10 = dt.timedelta( + weeks=1, + days=6, + hours=2, + minutes=5, + seconds=51, + milliseconds=10, + microseconds=742, + ) + + field = fields.TimeDelta(fields.TimeDelta.MICROSECONDS, float) + unit_value = dt.timedelta(microseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.MILLISECONDS, float) + unit_value = dt.timedelta(milliseconds=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.SECONDS, float) + assert math.isclose(field.serialize("d10", user), user.d10.total_seconds()) + + field = fields.TimeDelta(fields.TimeDelta.MINUTES, float) + unit_value = dt.timedelta(minutes=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.HOURS, float) + unit_value = dt.timedelta(hours=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.DAYS, float) + unit_value = dt.timedelta(days=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + field = fields.TimeDelta(fields.TimeDelta.WEEKS, float) + unit_value = dt.timedelta(weeks=1).total_seconds() + assert math.isclose( + field.serialize("d10", user), user.d10.total_seconds() / unit_value + ) + + with pytest.raises(ValueError): + fields.TimeDelta(fields.TimeDelta.SECONDS, str) + + def test_datetime_list_field(self): + obj = DateTimeList([dt.datetime.now(dt.timezone.utc), dt.datetime.now()]) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert all(type(each) is str for each in result) + + def test_list_field_serialize_none_returns_none(self): + obj = DateTimeList(None) + field = fields.List(fields.DateTime) + assert field.serialize("dtimes", obj) is None + + def test_list_field_work_with_generator_single_value(self): + def custom_generator(): + yield dt.datetime.now(dt.timezone.utc) + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 1 + + def test_list_field_work_with_generators_multiple_values(self): + def custom_generator(): + yield from [dt.datetime.now(dt.timezone.utc), dt.datetime.now()] + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + + def test_list_field_work_with_generators_empty_generator_returns_none_for_every_non_returning_yield_statement( # noqa: B950 + self, + ): + def custom_generator(): + yield + yield + + obj = DateTimeList(custom_generator()) + field = fields.List(fields.DateTime, allow_none=True) + result = field.serialize("dtimes", obj) + assert len(result) == 2 + assert result[0] is None + assert result[1] is None + + def test_list_field_work_with_set(self): + custom_set = {1, 2, 3} + obj = IntegerList(custom_set) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert 1 in result + assert 2 in result + assert 3 in result + + def test_list_field_work_with_custom_class_with_iterator_protocol(self): + class IteratorSupportingClass: + def __init__(self, iterable): + self.iterable = iterable + + def __iter__(self): + return iter(self.iterable) + + ints = IteratorSupportingClass([1, 2, 3]) + obj = IntegerList(ints) + field = fields.List(fields.Int) + result = field.serialize("ints", obj) + assert len(result) == 3 + assert result[0] == 1 + assert result[1] == 2 + assert result[2] == 3 + + def test_bad_list_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.List("string") + expected_msg = ( + "The list elements must be a subclass or instance of " + "marshmallow.base.FieldABC" + ) + with pytest.raises(ValueError, match=expected_msg): + fields.List(ASchema) + + def test_datetime_integer_tuple_field(self): + obj = DateTimeIntegerTuple((dt.datetime.now(dt.timezone.utc), 42)) + field = fields.Tuple([fields.DateTime, fields.Integer]) + result = field.serialize("dtime_int", obj) + assert type(result[0]) is str + assert type(result[1]) is int + + def test_tuple_field_serialize_none_returns_none(self): + obj = DateTimeIntegerTuple(None) + field = fields.Tuple([fields.DateTime, fields.Integer]) + assert field.serialize("dtime_int", obj) is None + + def test_bad_tuple_field(self): + class ASchema(Schema): + id = fields.Int() + + with pytest.raises(ValueError): + fields.Tuple(["string"]) + with pytest.raises(ValueError): + fields.Tuple(fields.String) + expected_msg = ( + 'Elements of "tuple_fields" must be subclasses or ' + "instances of marshmallow.base.FieldABC." + ) + with pytest.raises(ValueError, match=expected_msg): + fields.Tuple([ASchema]) + + def test_serialize_does_not_apply_validators(self, user): + field = fields.Field(validate=lambda x: False) + # No validation error raised + assert field.serialize("age", user) == user.age + + def test_constant_field_serialization(self, user): + field = fields.Constant("something") + assert field.serialize("whatever", user) == "something" + + def test_constant_is_always_included_in_serialized_data(self): + class MySchema(Schema): + foo = fields.Constant(42) + + sch = MySchema() + assert sch.dump({"bar": 24})["foo"] == 42 + assert sch.dump({"foo": 24})["foo"] == 42 + + def test_constant_field_serialize_when_omitted(self): + class MiniUserSchema(Schema): + name = fields.Constant("bill") + + s = MiniUserSchema() + assert s.dump({})["name"] == "bill" + + @pytest.mark.parametrize("FieldClass", ALL_FIELDS) + def test_all_fields_serialize_none_to_none(self, FieldClass): + field = FieldClass(allow_none=True) + res = field.serialize("foo", {"foo": None}) + assert res is None + + +class TestSchemaSerialization: + def test_serialize_with_missing_param_value(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + def test_serialize_with_missing_param_callable(self): + class AliasingUserSerializer(Schema): + name = fields.String() + birthdate = fields.DateTime(dump_default=lambda: dt.datetime(2017, 9, 29)) + + data = {"name": "Mick"} + result = AliasingUserSerializer().dump(data) + assert result["name"] == "Mick" + assert result["birthdate"] == "2017-09-29T00:00:00" + + +def test_serializing_named_tuple(): + Point = namedtuple("Point", ["x", "y"]) + + field = fields.Field() + + p = Point(x=4, y=2) + + assert field.serialize("x", p) == 4 + + +def test_serializing_named_tuple_with_meta(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(x=4, y=2) + + class PointSerializer(Schema): + class Meta: + fields = ("x", "y") + + serialized = PointSerializer().dump(p) + assert serialized["x"] == 4 + assert serialized["y"] == 2 + + +def test_serializing_slice(): + values = [{"value": value} for value in range(5)] + slice = itertools.islice(values, None) + + class ValueSchema(Schema): + value = fields.Int() + + serialized = ValueSchema(many=True).dump(slice) + assert serialized == values + + +# https://github.com/marshmallow-code/marshmallow/issues/1163 +def test_nested_field_many_serializing_generator(): + class MySchema(Schema): + name = fields.Str() + + class OtherSchema(Schema): + objects = fields.Nested(MySchema, many=True) + + def gen(): + yield {"name": "foo"} + yield {"name": "bar"} + + obj = {"objects": gen()} + data = OtherSchema().dump(obj) + + assert data.get("objects") == [{"name": "foo"}, {"name": "bar"}] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_utils.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..44baa71f428818a343a77bb916759d6d75112a17 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_utils.py @@ -0,0 +1,282 @@ +import datetime as dt +from collections import namedtuple +from copy import copy, deepcopy +from functools import partial + +import pytest + +from marshmallow import Schema, fields, utils +from tests.base import assert_date_equal, assert_time_equal, central + + +def test_missing_singleton_copy(): + assert copy(utils.missing) is utils.missing + assert deepcopy(utils.missing) is utils.missing + + +PointNT = namedtuple("PointNT", ["x", "y"]) + + +class PointClass: + def __init__(self, x, y): + self.x = x + self.y = y + + +class PointDict(dict): + def __init__(self, x, y): + super().__init__({"x": x}) + self.y = y + + +@pytest.mark.parametrize( + "obj", [PointNT(24, 42), PointClass(24, 42), PointDict(24, 42), {"x": 24, "y": 42}] +) +def test_get_value_from_object(obj): + assert utils.get_value(obj, "x") == 24 + assert utils.get_value(obj, "y") == 42 + + +def test_get_value_from_namedtuple_with_default(): + p = PointNT(x=42, y=None) + # Default is only returned if key is not found + assert utils.get_value(p, "z", default=123) == 123 + # since 'y' is an attribute, None is returned instead of the default + assert utils.get_value(p, "y", default=123) is None + + +class Triangle: + def __init__(self, p1, p2, p3): + self.p1 = p1 + self.p2 = p2 + self.p3 = p3 + self.points = [p1, p2, p3] + + +def test_get_value_for_nested_object(): + tri = Triangle(p1=PointClass(1, 2), p2=PointNT(3, 4), p3={"x": 5, "y": 6}) + assert utils.get_value(tri, "p1.x") == 1 + assert utils.get_value(tri, "p2.x") == 3 + assert utils.get_value(tri, "p3.x") == 5 + + +# regression test for https://github.com/marshmallow-code/marshmallow/issues/62 +def test_get_value_from_dict(): + d = dict(items=["foo", "bar"], keys=["baz", "quux"]) + assert utils.get_value(d, "items") == ["foo", "bar"] + assert utils.get_value(d, "keys") == ["baz", "quux"] + + +def test_get_value(): + lst = [1, 2, 3] + assert utils.get_value(lst, 1) == 2 + + class MyInt(int): + pass + + assert utils.get_value(lst, MyInt(1)) == 2 + + +def test_set_value(): + d = {} + utils.set_value(d, "foo", 42) + assert d == {"foo": 42} + + d = {} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": {}} + utils.set_value(d, "foo.bar", 42) + assert d == {"foo": {"bar": 42}} + + d = {"foo": 42} + with pytest.raises(ValueError): + utils.set_value(d, "foo.bar", 42) + + +def test_is_keyed_tuple(): + Point = namedtuple("Point", ["x", "y"]) + p = Point(24, 42) + assert utils.is_keyed_tuple(p) is True + t = (24, 42) + assert utils.is_keyed_tuple(t) is False + d = {"x": 42, "y": 24} + assert utils.is_keyed_tuple(d) is False + s = "xy" + assert utils.is_keyed_tuple(s) is False + lst = [24, 42] + assert utils.is_keyed_tuple(lst) is False + + +def test_is_collection(): + assert utils.is_collection([1, "foo", {}]) is True + assert utils.is_collection(("foo", 2.3)) is True + assert utils.is_collection({"foo": "bar"}) is False + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "Sun, 10 Nov 2013 01:23:45 -0000"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "Sun, 10 Nov 2013 01:23:45 +0000", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "Sun, 10 Nov 2013 01:23:45 -0600", + ), + ], +) +def test_rfc_format(value, expected): + assert utils.rfcformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (dt.datetime(2013, 11, 10, 1, 23, 45), "2013-11-10T01:23:45"), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45.123456+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + "2013-11-10T01:23:45+00:00", + ), + ( + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + "2013-11-10T01:23:45-06:00", + ), + ], +) +def test_isoformat(value, expected): + assert utils.isoformat(value) == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("Sun, 10 Nov 2013 01:23:45 -0000", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "Sun, 10 Nov 2013 01:23:45 +0000", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + "Sun, 10 Nov 2013 01:23:45 -0600", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_rfc(value, expected): + result = utils.from_rfc(value) + assert type(result) is dt.datetime + assert result == expected + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("2013-11-10T01:23:45", dt.datetime(2013, 11, 10, 1, 23, 45)), + ( + "2013-11-10T01:23:45+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), + ), + ( + # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 + "2013-11-10T01:23:45.123+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123000, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45.123456+00:00", + dt.datetime(2013, 11, 10, 1, 23, 45, 123456, tzinfo=dt.timezone.utc), + ), + ( + "2013-11-10T01:23:45-06:00", + dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=central), + ), + ], +) +def test_from_iso_datetime(value, expected): + result = utils.from_iso_datetime(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_iso_time_with_microseconds(): + t = dt.time(1, 23, 45, 6789) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_time_without_microseconds(): + t = dt.time(1, 23, 45) + formatted = t.isoformat() + result = utils.from_iso_time(formatted) + assert type(result) is dt.time + assert_time_equal(result, t) + + +def test_from_iso_date(): + d = dt.date(2014, 8, 21) + iso_date = d.isoformat() + result = utils.from_iso_date(iso_date) + assert type(result) is dt.date + assert_date_equal(result, d) + + +@pytest.mark.parametrize( + ("value", "expected"), + [ + (1676386740, dt.datetime(2023, 2, 14, 14, 59, 00)), + (1676386740.58, dt.datetime(2023, 2, 14, 14, 59, 00, 580000)), + ], +) +def test_from_timestamp(value, expected): + result = utils.from_timestamp(value) + assert type(result) is dt.datetime + assert result == expected + + +def test_from_timestamp_with_negative_value(): + value = -10 + with pytest.raises(ValueError, match=r"Not a valid POSIX timestamp"): + utils.from_timestamp(value) + + +def test_from_timestamp_with_overflow_value(): + value = 9223372036854775 + with pytest.raises(ValueError): + utils.from_timestamp(value) + + +def test_get_func_args(): + def f1(foo, bar): + pass + + f2 = partial(f1, "baz") + + class F3: + def __call__(self, foo, bar): + pass + + f3 = F3() + + for func in [f1, f2, f3]: + assert utils.get_func_args(func) == ["foo", "bar"] + + +# Regression test for https://github.com/marshmallow-code/marshmallow/issues/540 +def test_function_field_using_type_annotation(): + def get_split_words(value: str): # noqa + return value.split(";") + + class MySchema(Schema): + friends = fields.Function(deserialize=get_split_words) + + data = {"friends": "Clark;Alfred;Robin"} + result = MySchema().load(data) + assert result == {"friends": ["Clark", "Alfred", "Robin"]} diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_validate.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..fcda4e81639892ad4a2123c6db71f6f45a6bf764 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_validate.py @@ -0,0 +1,983 @@ +"""Tests for marshmallow.validate""" + +import re + +import pytest + +from marshmallow import ValidationError, validate + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "https://example.org", + "ftp://example.org", + "ftps://example.org", + "http://example.co.jp", + "http://www.example.com/a%C2%B1b", + "http://www.example.com/~username/", + "http://info.example.com/?fred", + "http://xn--mgbh0fb.xn--kgbechtv/", + "http://example.com/blue/red%3Fand+green", + "http://www.example.com/?array%5Bkey%5D=value", + "http://xn--rsum-bpad.example.org/", + "http://123.45.67.8/", + "http://123.45.67.8:8329/", + "http://[2001:db8::ff00:42]:8329", + "http://[2001::1]:8329", + "http://www.example.com:8000/foo", + "http://user@example.com", + "http://user:pass@example.com", + "http://:pass@example.com", + "http://@example.com", + "http://AZaz09-._~%2A!$&'()*+,;=:@example.com", + ], +) +def test_url_absolute_valid(valid_url): + validator = validate.URL(relative=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http:///example.com/", + "https:///example.com/", + "https://example.org\\", + "https://example.org\n", + "ftp:///example.com/", + "ftps:///example.com/", + "http//example.org", + "http:///", + "http:/example.org", + "foo://example.org", + "../icons/logo.gif", + "http://2001:db8::ff00:42:8329", + "http://[192.168.1.1]:8329", + "abc", + "..", + "/", + " ", + "", + None, + "http://user@pass@example.com", + "http://@pass@example.com", + "http://@@example.com", + "http://^@example.com", + "http://%0G@example.com", + "http://%@example.com", + ], +) +def test_url_absolute_invalid(invalid_url): + validator = validate.URL(relative=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + "/foo/bar", + "/foo?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_valid(valid_url): + validator = validate.URL(relative=True) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( # noqa: W605 + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + None, + ], +) +def test_url_relative_invalid(invalid_url): + validator = validate.URL(relative=True) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "/foo/bar", + "/foo?bar", + "?bar", + "/foo?bar#baz", + ], +) +def test_url_relative_only_valid(valid_url): + validator = validate.URL(relative=True, absolute=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example.org", + "http://example.org\n", + "suppliers.html", + "../icons/logo.gif", + "icons/logo.gif", + "../.../g", + "...", + "\\", + " ", + "", + "http://example.org", + "http://123.45.67.8/", + "http://example.com/foo/bar/../baz", + "https://example.com/../icons/logo.gif", + "http://example.com/./icons/logo.gif", + "ftp://example.com/../../../../g", + "http://example.com/g?y/./x", + ], +) +def test_url_relative_only_invalid(invalid_url): + validator = validate.URL(relative=True, absolute=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +@pytest.mark.parametrize( + "valid_url", + [ + "http://example.org", + "http://123.45.67.8/", + "http://example", + "http://example.", + "http://example:80", + "http://user.name:pass.word@example", + "http://example/foo/bar", + ], +) +def test_url_dont_require_tld_valid(valid_url): + validator = validate.URL(require_tld=False) + assert validator(valid_url) == valid_url + + +@pytest.mark.parametrize( + "invalid_url", + [ + "http//example", + "http://example\n", + "http://.example.org", + "http:///foo/bar", + "http:// /foo/bar", + "", + None, + ], +) +def test_url_dont_require_tld_invalid(invalid_url): + validator = validate.URL(require_tld=False) + with pytest.raises(ValidationError): + validator(invalid_url) + + +def test_url_custom_scheme(): + validator = validate.URL() + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_relative_and_custom_schemes(): + validator = validate.URL(relative=True) + # By default, ws not allowed + url = "ws://test.test" + with pytest.raises(ValidationError): + validator(url) + + validator = validate.URL(relative=True, schemes={"http", "https", "ws"}) + assert validator(url) == url + + +def test_url_custom_message(): + validator = validate.URL(error="{input} ain't an URL") + with pytest.raises(ValidationError, match="invalid ain't an URL"): + validator("invalid") + + +def test_url_repr(): + assert repr( + validate.URL(relative=False, error=None) + ) == "".format("Not a valid URL.") + assert repr( + validate.URL(relative=True, error="foo") + ) == "".format("foo") + assert repr( + validate.URL(relative=True, absolute=False, error="foo") + ) == "".format("foo") + + +def test_url_rejects_invalid_relative_usage(): + with pytest.raises( + ValueError, + match="URL validation cannot set both relative and absolute to False", + ): + validate.URL(relative=False, absolute=False) + + +@pytest.mark.parametrize( + "valid_email", + [ + "niceandsimple@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM", + "very.common@example.com", + "a.little.lengthy.but.fine@a.iana-servers.net", + "disposable.style.email.with+symbol@example.com", + '"very.unusual.@.unusual.com"@example.com', + "!#$%&'*+-/=?^_`{}|~@example.org", + "niceandsimple@[64.233.160.0]", + "niceandsimple@localhost", + "josé@blah.com", + "δοκ.ιμή@παράδειγμα.δοκιμή", + ], +) +def test_email_valid(valid_email): + validator = validate.Email() + assert validator(valid_email) == valid_email + + +@pytest.mark.parametrize( + "invalid_email", + [ + "niceandsimple\n@example.com", + "NiCeAnDsImPlE@eXaMpLe.CoM\n", + 'a"b(c)d,e:f;gi[j\\k]l@example.com', + 'just"not"right@example.com', + 'this is"not\allowed@example.com', + 'this\\ still\\"not\\\\allowed@example.com', + '"much.more unusual"@example.com', + '"very.(),:;<>[]".VERY."very@\\ "very".unusual"@strange.example.com', + '" "@example.org', + "user@example", + "@nouser.com", + "example.com", + "user", + "", + None, + ], +) +def test_email_invalid(invalid_email): + validator = validate.Email() + with pytest.raises(ValidationError): + validator(invalid_email) + + +def test_email_custom_message(): + validator = validate.Email(error="{input} is not an email addy.") + with pytest.raises(ValidationError, match="invalid is not an email addy."): + validator("invalid") + + +def test_email_repr(): + assert repr(validate.Email(error=None)) == "".format( + "Not a valid email address." + ) + assert repr(validate.Email(error="foo")) == "".format("foo") + + +def test_range_min(): + assert validate.Range(1, 2)(1) == 1 + assert validate.Range(0)(1) == 1 + assert validate.Range()(1) == 1 + assert validate.Range(min_inclusive=False, max_inclusive=False)(1) == 1 + assert validate.Range(1, 1)(1) == 1 + + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2, 3)(1) + with pytest.raises(ValidationError, match="Must be greater than or equal to 2"): + validate.Range(2)(1) + with pytest.raises(ValidationError, match="Must be greater than 1"): + validate.Range(1, 2, min_inclusive=False, max_inclusive=True, error=None)(1) + with pytest.raises(ValidationError, match="less than 1"): + validate.Range(1, 1, min_inclusive=True, max_inclusive=False, error=None)(1) + + +def test_range_max(): + assert validate.Range(1, 2)(2) == 2 + assert validate.Range(None, 2)(2) == 2 + assert validate.Range()(2) == 2 + assert validate.Range(min_inclusive=False, max_inclusive=False)(2) == 2 + assert validate.Range(2, 2)(2) == 2 + + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(0, 1)(2) + with pytest.raises(ValidationError, match="less than or equal to 1"): + validate.Range(None, 1)(2) + with pytest.raises(ValidationError, match="less than 2"): + validate.Range(1, 2, min_inclusive=True, max_inclusive=False, error=None)(2) + with pytest.raises(ValidationError, match="greater than 2"): + validate.Range(2, 2, min_inclusive=False, max_inclusive=True, error=None)(2) + + +def test_range_custom_message(): + v = validate.Range(2, 3, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="1 is not between 2 and 3"): + v(1) + + v = validate.Range(2, None, error="{input} is less than {min}") + with pytest.raises(ValidationError, match="1 is less than 2"): + v(1) + + v = validate.Range(None, 3, error="{input} is greater than {max}") + with pytest.raises(ValidationError, match="4 is greater than 3"): + v(4) + + +def test_range_repr(): + assert ( + repr( + validate.Range( + min=None, max=None, error=None, min_inclusive=True, max_inclusive=True + ) + ) + == "" # noqa: B950 + ) + assert ( + repr( + validate.Range( + min=1, max=3, error="foo", min_inclusive=False, max_inclusive=False + ) + ) + == "".format( # noqa: B950 + "foo" + ) + ) + + +def test_length_min(): + assert validate.Length(3, 5)("foo") == "foo" + assert validate.Length(3, 5)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(0)("a") == "a" + assert validate.Length(0)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(1, 1)("a") == "a" + assert validate.Length(1, 1)([1]) == [1] + + with pytest.raises(ValidationError): + validate.Length(4, 5)("foo") + with pytest.raises(ValidationError): + validate.Length(4, 5)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(5)("foo") + with pytest.raises(ValidationError): + validate.Length(5)([1, 2, 3]) + + +def test_length_max(): + assert validate.Length(1, 3)("foo") == "foo" + assert validate.Length(1, 3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(None, 1)("a") == "a" + assert validate.Length(None, 1)([1]) == [1] + assert validate.Length()("") == "" + assert validate.Length()([]) == [] + assert validate.Length(2, 2)("ab") == "ab" + assert validate.Length(2, 2)([1, 2]) == [1, 2] + + with pytest.raises(ValidationError): + validate.Length(1, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(1, 2)([1, 2, 3]) + with pytest.raises(ValidationError): + validate.Length(None, 2)("foo") + with pytest.raises(ValidationError): + validate.Length(None, 2)([1, 2, 3]) + + +def test_length_equal(): + assert validate.Length(equal=3)("foo") == "foo" + assert validate.Length(equal=3)([1, 2, 3]) == [1, 2, 3] + assert validate.Length(equal=None)("") == "" + assert validate.Length(equal=None)([]) == [] + + with pytest.raises(ValidationError): + validate.Length(equal=2)("foo") + with pytest.raises(ValidationError): + validate.Length(equal=2)([1, 2, 3]) + + with pytest.raises(ValueError): + validate.Length(1, None, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(None, 5, equal=3)("foo") + with pytest.raises(ValueError): + validate.Length(1, 5, equal=3)("foo") + + +def test_length_custom_message(): + v = validate.Length(5, 6, error="{input} is not between {min} and {max}") + with pytest.raises(ValidationError, match="foo is not between 5 and 6"): + v("foo") + + v = validate.Length(5, None, error="{input} is shorter than {min}") + with pytest.raises(ValidationError, match="foo is shorter than 5"): + v("foo") + + v = validate.Length(None, 2, error="{input} is longer than {max}") + with pytest.raises(ValidationError, match="foo is longer than 2"): + v("foo") + + v = validate.Length(None, None, equal=4, error="{input} does not have {equal}") + with pytest.raises(ValidationError, match="foo does not have 4"): + v("foo") + + +def test_length_repr(): + assert ( + repr(validate.Length(min=None, max=None, error=None, equal=None)) + == "" + ) + assert repr( + validate.Length(min=1, max=3, error="foo", equal=None) + ) == "".format("foo") + assert repr( + validate.Length(min=None, max=None, error="foo", equal=5) + ) == "".format("foo") + + +def test_equal(): + assert validate.Equal("a")("a") == "a" + assert validate.Equal(1)(1) == 1 + assert validate.Equal([1])([1]) == [1] + + with pytest.raises(ValidationError): + validate.Equal("b")("a") + with pytest.raises(ValidationError): + validate.Equal(2)(1) + with pytest.raises(ValidationError): + validate.Equal([2])([1]) + + +def test_equal_custom_message(): + v = validate.Equal("a", error="{input} is not equal to {other}.") + with pytest.raises(ValidationError, match="b is not equal to a."): + v("b") + + +def test_equal_repr(): + assert repr( + validate.Equal(comparable=123, error=None) + ) == "".format("Must be equal to {other}.") + assert repr( + validate.Equal(comparable=123, error="foo") + ) == "".format("foo") + + +def test_regexp_str(): + assert validate.Regexp(r"a")("a") == "a" + assert validate.Regexp(r"\w")("_") == "_" + assert validate.Regexp(r"\s")(" ") == " " + assert validate.Regexp(r"1")("1") == "1" + assert validate.Regexp(r"[0-9]+")("1") == "1" + assert validate.Regexp(r"a", re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(r"[0-9]+")("a") + with pytest.raises(ValidationError): + validate.Regexp(r"[a-z]+")("1") + with pytest.raises(ValidationError): + validate.Regexp(r"a")("A") + + +def test_regexp_compile(): + assert validate.Regexp(re.compile(r"a"))("a") == "a" + assert validate.Regexp(re.compile(r"\w"))("_") == "_" + assert validate.Regexp(re.compile(r"\s"))(" ") == " " + assert validate.Regexp(re.compile(r"1"))("1") == "1" + assert validate.Regexp(re.compile(r"[0-9]+"))("1") == "1" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE))("A") == "A" + assert validate.Regexp(re.compile(r"a", re.IGNORECASE), re.IGNORECASE)("A") == "A" + + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[0-9]+"))("a") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"[a-z]+"))("1") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"))("A") + with pytest.raises(ValidationError): + validate.Regexp(re.compile(r"a"), re.IGNORECASE)("A") + + +def test_regexp_custom_message(): + rex = r"[0-9]+" + v = validate.Regexp(rex, error="{input} does not match {regex}") + with pytest.raises(ValidationError, match="a does not match"): + v("a") + + +def test_regexp_repr(): + assert repr( + validate.Regexp(regex="abc", flags=0, error=None) + ) == "".format( + re.compile("abc"), "String does not match expected pattern." + ) + assert repr( + validate.Regexp(regex="abc", flags=re.IGNORECASE, error="foo") + ) == "".format( + re.compile("abc", re.IGNORECASE), "foo" + ) + + +def test_predicate(): + class Dummy: + def _true(self): + return True + + def _false(self): + return False + + def _list(self): + return [1, 2, 3] + + def _empty(self): + return [] + + def _identity(self, arg): + return arg + + d = Dummy() + + assert validate.Predicate("_true")(d) == d + assert validate.Predicate("_list")(d) == d + assert validate.Predicate("_identity", arg=True)(d) == d + assert validate.Predicate("_identity", arg=1)(d) == d + assert validate.Predicate("_identity", arg="abc")(d) == d + + with pytest.raises(ValidationError, match="Invalid input."): + validate.Predicate("_false")(d) + with pytest.raises(ValidationError): + validate.Predicate("_empty")(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=False)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg=0)(d) + with pytest.raises(ValidationError): + validate.Predicate("_identity", arg="")(d) + + +def test_predicate_custom_message(): + class Dummy: + def _false(self): + return False + + def __str__(self): + return "Dummy" + + d = Dummy() + with pytest.raises(ValidationError, match="Dummy._false is invalid!"): + validate.Predicate("_false", error="{input}.{method} is invalid!")(d) + + +def test_predicate_repr(): + assert repr( + validate.Predicate(method="foo", error=None) + ) == "".format( + "foo", {}, "Invalid input." + ) + assert repr( + validate.Predicate(method="foo", error="bar", zoo=1) + ) == "".format( + "foo", {"zoo": 1}, "bar" + ) + + +def test_noneof(): + assert validate.NoneOf([1, 2, 3])(4) == 4 + assert validate.NoneOf("abc")("d") == "d" + assert validate.NoneOf("")([]) == [] + assert validate.NoneOf([])("") == "" + assert validate.NoneOf([])([]) == [] + assert validate.NoneOf([1, 2, 3])(None) is None + + with pytest.raises(ValidationError, match="Invalid input."): + validate.NoneOf([1, 2, 3])(3) + with pytest.raises(ValidationError): + validate.NoneOf("abc")("c") + with pytest.raises(ValidationError): + validate.NoneOf([1, 2, None])(None) + with pytest.raises(ValidationError): + validate.NoneOf("")("") + + +def test_noneof_custom_message(): + with pytest.raises(ValidationError, match=""): + validate.NoneOf([1, 2], error="")(1) + + none_of = validate.NoneOf([1, 2], error="{input} cannot be one of {values}") + with pytest.raises(ValidationError, match="1 cannot be one of 1, 2"): + none_of(1) + + +def test_noneof_repr(): + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error=None) + ) == "".format("Invalid input.") + assert repr( + validate.NoneOf(iterable=[1, 2, 3], error="foo") + ) == "".format("foo") + + +def test_oneof(): + assert validate.OneOf([1, 2, 3])(2) == 2 + assert validate.OneOf("abc")("b") == "b" + assert validate.OneOf("")("") == "" + assert validate.OneOf(dict(a=0, b=1))("a") == "a" + assert validate.OneOf((1, 2, None))(None) is None + + with pytest.raises(ValidationError, match="Must be one of: 1, 2, 3."): + validate.OneOf([1, 2, 3])(4) + with pytest.raises(ValidationError): + validate.OneOf("abc")("d") + with pytest.raises(ValidationError): + validate.OneOf((1, 2, 3))(None) + with pytest.raises(ValidationError): + validate.OneOf([])([]) + with pytest.raises(ValidationError): + validate.OneOf(())(()) + with pytest.raises(ValidationError): + validate.OneOf(dict(a=0, b=1))(0) + with pytest.raises(ValidationError): + validate.OneOf("123")(1) + + +def test_oneof_options(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("3", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2, 3], ["one", "two"]) + expected = [("1", "one"), ("2", "two"), ("3", "")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2], ["one", "two", "three"]) + expected = [("1", "one"), ("2", "two"), ("", "three")] + assert list(oneof.options()) == expected + + oneof = validate.OneOf([1, 2]) + expected = [("1", ""), ("2", "")] + assert list(oneof.options()) == expected + + +def test_oneof_text(): + oneof = validate.OneOf([1, 2, 3], ["one", "two", "three"]) + assert oneof.choices_text == "1, 2, 3" + assert oneof.labels_text == "one, two, three" + + oneof = validate.OneOf([1], ["one"]) + assert oneof.choices_text == "1" + assert oneof.labels_text == "one" + + oneof = validate.OneOf(dict(a=0, b=1)) + assert ", ".join(sorted(oneof.choices_text.split(", "))) == "a, b" + assert oneof.labels_text == "" + + +def test_oneof_custom_message(): + oneof = validate.OneOf([1, 2, 3], error="{input} is not one of {choices}") + expected = "4 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + oneof = validate.OneOf( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4 is not one of one, two, three" + with pytest.raises(ValidationError): + oneof(4) + assert expected in str(expected) + + +def test_oneof_repr(): + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "Must be one of: {choices}." + ) + assert repr( + validate.OneOf(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsonly_in_list(): + assert validate.ContainsOnly([])([]) == [] + assert validate.ContainsOnly([1, 2, 3])([1]) == [1] + assert validate.ContainsOnly([1, 1, 2])([1, 1]) == [1, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2]) == [1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 1]) == [2, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsOnly([1, 2, 3])([3, 1, 2]) == [3, 1, 2] + assert validate.ContainsOnly([1, 2, 3])([2, 3, 1]) == [2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([1, 2, 3, 1]) == [1, 2, 3, 1] + assert validate.ContainsOnly([1, 2, 3])([]) == [] + + with pytest.raises( + ValidationError, + match="One or more of the choices you made was not in: 1, 2, 3.", + ): + validate.ContainsOnly([1, 2, 3])([4]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_contains_only_unhashable_types(): + assert validate.ContainsOnly([[1], [2], [3]])([[1]]) == [[1]] + assert validate.ContainsOnly([[1], [1], [2]])([[1], [1]]) == [[1], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2]]) == [[1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [1]]) == [[2], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([[1], [2], [3]]) == [[1], [2], [3]] + assert validate.ContainsOnly([[1], [2], [3]])([[3], [1], [2]]) == [[3], [1], [2]] + assert validate.ContainsOnly([[1], [2], [3]])([[2], [3], [1]]) == [[2], [3], [1]] + assert validate.ContainsOnly([[1], [2], [3]])([]) == [] + + with pytest.raises(ValidationError): + validate.ContainsOnly([[1], [2], [3]])([[4]]) + with pytest.raises(ValidationError): + validate.ContainsOnly([])([1]) + + +def test_containsonly_in_tuple(): + assert validate.ContainsOnly(())(()) == () + assert validate.ContainsOnly((1, 2, 3))((1,)) == (1,) + assert validate.ContainsOnly((1, 1, 2))((1, 1)) == (1, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2)) == (1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 1)) == (2, 1) + assert validate.ContainsOnly((1, 2, 3))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsOnly((1, 2, 3))((3, 1, 2)) == (3, 1, 2) + assert validate.ContainsOnly((1, 2, 3))((2, 3, 1)) == (2, 3, 1) + assert validate.ContainsOnly((1, 2, 3))(()) == tuple() + with pytest.raises(ValidationError): + validate.ContainsOnly((1, 2, 3))((4,)) + with pytest.raises(ValidationError): + validate.ContainsOnly(())((1,)) + + +def test_contains_only_in_string(): + assert validate.ContainsOnly("")("") == "" + assert validate.ContainsOnly("abc")("a") == "a" + assert validate.ContainsOnly("aab")("aa") == "aa" + assert validate.ContainsOnly("abc")("ab") == "ab" + assert validate.ContainsOnly("abc")("ba") == "ba" + assert validate.ContainsOnly("abc")("abc") == "abc" + assert validate.ContainsOnly("abc")("cab") == "cab" + assert validate.ContainsOnly("abc")("bca") == "bca" + assert validate.ContainsOnly("abc")("") == "" + + with pytest.raises(ValidationError): + validate.ContainsOnly("abc")("d") + with pytest.raises(ValidationError): + validate.ContainsOnly("")("a") + + +def test_containsonly_custom_message(): + containsonly = validate.ContainsOnly( + [1, 2, 3], error="{input} is not one of {choices}" + ) + expected = "4, 5 is not one of 1, 2, 3" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + containsonly = validate.ContainsOnly( + [1, 2, 3], ["one", "two", "three"], error="{input} is not one of {labels}" + ) + expected = "4, 5 is not one of one, two, three" + with pytest.raises(ValidationError): + containsonly([4, 5]) + assert expected in str(expected) + + +def test_containsonly_repr(): + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=None, error=None) + ) == "".format( + "One or more of the choices you made was not in: {choices}." + ) + assert repr( + validate.ContainsOnly(choices=[1, 2, 3], labels=["a", "b", "c"], error="foo") + ) == "".format( + ["a", "b", "c"], "foo" + ) + + +def test_containsnoneof_error_message(): + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1" + ): + validate.ContainsNoneOf([1])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: 1, 2, 3" + ): + validate.ContainsNoneOf([1, 2, 3])([1]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: one, two" + ): + validate.ContainsNoneOf(["one", "two"])(["one"]) + + with pytest.raises( + ValidationError, match="One or more of the choices you made was in: @, !, &, ?" + ): + validate.ContainsNoneOf("@!&?")("@") + + +def test_containsnoneof_in_list(): + assert validate.ContainsNoneOf([])([]) == [] + assert validate.ContainsNoneOf([])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([4])([1, 2, 3]) == [1, 2, 3] + assert validate.ContainsNoneOf([2])([1, 3, 4]) == [1, 3, 4] + assert validate.ContainsNoneOf([1, 2, 3])([4]) == [4] + assert validate.ContainsNoneOf([4])([1, 1, 1, 1]) == [1, 1, 1, 1] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 1, 1])([1, 2, 3]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2])([1, 2]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1])([1, 1, 1, 1]) + + +def test_containsnoneof_unhashable_types(): + assert validate.ContainsNoneOf([[1], [2], [3]])([]) == [] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4]]) == [[4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [4]]) == [[4], [4]] + assert validate.ContainsNoneOf([[1], [2], [3]])([[4], [5]]) == [[4], [5]] + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[1], [2], [3]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[3], [2], [1]]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([[1], [2], [3]])([[2], [3], [1]]) + + +def test_containsnoneof_in_tuple(): + assert validate.ContainsNoneOf(())(()) == () + assert validate.ContainsNoneOf(())((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((4,))((1, 2, 3)) == (1, 2, 3) + assert validate.ContainsNoneOf((2,))((1, 3, 4)) == (1, 3, 4) + assert validate.ContainsNoneOf((1, 2, 3))((4,)) == (4,) + assert validate.ContainsNoneOf((4,))((1, 1, 1, 1)) == (1, 1, 1, 1) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 1, 1))((1, 2, 3)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2))((1, 2)) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1,))((1, 1, 1, 1)) + + +def test_containsnoneof_in_string(): + assert validate.ContainsNoneOf("")("") == "" + assert validate.ContainsNoneOf("")("abc") == "abc" + assert validate.ContainsNoneOf("d")("abc") == "abc" + assert validate.ContainsNoneOf("b")("acd") == "acd" + assert validate.ContainsNoneOf("abc")("d") == "d" + assert validate.ContainsNoneOf("d")("aaaa") == "aaaa" + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("aaa")("abc") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("ab")("ab") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf("a")("aaaa") + + +def test_containsnoneof_custom_message(): + validator = validate.ContainsNoneOf( + [1, 2, 3], error="{input} was in the banned list: {values}" + ) + expected = "1 was in the banned list: 1, 2, 3" + with pytest.raises(ValidationError, match=expected): + validator([1]) + + +def test_containsnoneof_mixing_types(): + with pytest.raises(ValidationError): + validate.ContainsNoneOf("abc")(["a"]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf(["a", "b", "c"])("a") + + with pytest.raises(ValidationError): + validate.ContainsNoneOf((1, 2, 3))([1]) + + with pytest.raises(ValidationError): + validate.ContainsNoneOf([1, 2, 3])((1,)) + + +def is_even(value): + if value % 2 != 0: + raise ValidationError("Not an even value.") + + +def test_and(): + validator = validate.And(validate.Range(min=0), is_even) + assert validator(2) + with pytest.raises(ValidationError) as excinfo: + validator(-1) + errors = excinfo.value.messages + assert errors == ["Must be greater than or equal to 0.", "Not an even value."] + + validator_with_composition = validate.And(validator, validate.Range(max=6)) + assert validator_with_composition(4) + with pytest.raises(ValidationError) as excinfo: + validator_with_composition(7) + + errors = excinfo.value.messages + assert errors == ["Not an even value.", "Must be less than or equal to 6."] diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_version_attributes.py b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_version_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..d233b39ddf97363d18e0b8499f2bd3601005a322 --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tests/test_version_attributes.py @@ -0,0 +1,15 @@ +# ruff: noqa: B018 +import pytest + +import marshmallow + + +def test_version_attributes_deprecated(): + with pytest.warns(DeprecationWarning): + marshmallow.__version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__parsed_version__ + + with pytest.warns(DeprecationWarning): + marshmallow.__version_info__ diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tox.ini b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..526cb0be346c76109c1570430aa5f666d1f3114d --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/tests/trusted/tox.ini @@ -0,0 +1,35 @@ +[tox] +envlist = lint,mypy-test,py{39,310,311,312,313},docs + +[testenv] +extras = tests +commands = pytest {posargs} + +[testenv:lint] +deps = pre-commit~=3.5 +skip_install = true +commands = pre-commit run --all-files + +[testenv:mypy-test] +deps = mypy +commands = mypy --show-error-codes --warn-unused-ignores tests/mypy_test_cases/ + +[testenv:docs] +extras = docs +commands = sphinx-build docs/ docs/_build {posargs} + +; Below tasks are for development only (not run in CI) + +[testenv:watch-docs] +deps = sphinx-autobuild +extras = docs +commands = sphinx-autobuild --open-browser docs/ docs/_build {posargs} --watch src/marshmallow --delay 2 + +[testenv:watch-readme] +deps = restview +skip_install = true +commands = restview README.rst + +[testenv:benchmark] +usedevelop = true +commands = python performance/benchmark.py --iterations=100 --repeat=3 diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/validation/canaries/original-bug.sh b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/validation/openenv.json b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/marshmallow-code__marshmallow.9716fc62.func_basic__0jrkbh70/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/LICENSE.source b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..611d35661f933a4469c941e6c97578c22673b4ab --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/LICENSE.source @@ -0,0 +1,7 @@ +Copyright (C) 2013 Markus Siemens + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/adapter.json b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..a229e181e0ccee11e14ee6da801294ece04c20b3 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/adapter.json @@ -0,0 +1,138 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "checker_revision": { + "new_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "old_checker_sha256": "ce5f5ada4c63ab61c57177833687df68fcfe04df971699cb3e6ceada5722d2ed", + "old_plan_sha256": "6c91fe8ccbd5813aa1b13f310318d50d40222feb158abf0812d48856ff829d19", + "old_task_digest": "a6da42f8f9ca70d81a50034b0c52a9bca9032c3d6488792a1ebe6a0a6ed4b5e2", + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_grader_sha256": "48d05896ed5af21d9b8ab20e1b3470a370ab635d1c0c6ebf4e8851761c184532", + "runtime_qualified": false, + "source_tests_or_panels_changed": false, + "version": "matched-failure-precedence-v2" + }, + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "0551e0806afd99add5cb7c6184a7e0b4813c16aa421c4031e64e7e3a27b44236", + "gold_patch_sha256": "d7be2fd072b6b80aa3e760a4c6a32d707cd60939d30851b646240b08d23c8b07", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "90562f69ad208d57c220ee7750d4cfe91695ffdde581d352a03cd93a90990e6f", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Tinydb10644a0e", + "profile_lines": [ + 1020, + 1023 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "upstream_repo": "msiemens/tinydb" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "72edb10ef157bf690079725d03ea8bc1a9768177d809d0349a616f99d1752933", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/msiemens__tinydb.10644a0e.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install 'pytest>=7.2,<8' 'pytest-cov>=4,<5'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4318e4525086b9ab07b2269c7a6f1ff2003ad01a663b94f56e772d63655166be", + "pytest.ini": "2c2ccbf97dabef288fd402c4bb1ddba4d3baa35d1f903a3f5735633c1d504b7c" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "325398e5f584172582480e327ab123a2b58c240b", + "source_completion_sha256": "cca3cc73a00b1bb6d2823bb46523b9eac58f0538fa95799bb542248190685ffe", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:msiemens__tinydb.10644a0e.combine_file__0176isok", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "278700580526dd378f18f40b641885ec78df63e1", + "instruction_sha256": "e72ed6224bacc52f43645133460f4ba0c52c5e1f6f57086f536ee6003cbfd02f", + "is_fork": true, + "learner_path": "tasks/4feabf9a847b20ba0e24109c/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "actual_upstream_url": "https://raw.githubusercontent.com/msiemens/tinydb/10644a0e07ad180c5b756aba272ee6b0dbd12df8/LICENSE", + "reviewed": true, + "sha256": "b0e2a2d39271e3d96b717d7be8235ac413d74797bf7f742f0801cfaad6c8c912", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/msiemens__tinydb.10644a0e/325398e5f584172582480e327ab123a2b58c240b/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "patch_sha256": "74761a8f574379f7758dbd1d8366749758357275c15c27c2e41083ca595ad8ae", + "provenance_path": "tasks/4feabf9a847b20ba0e24109c/source-proof.json", + "repository_lineage": [ + "swesmith/msiemens__tinydb.10644a0e", + "msiemens/tinydb" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "325398e5f584172582480e327ab123a2b58c240b", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "a603f16b47d665761852fbe708c19b0c071cd1e8", + "source_kind": "mutation", + "source_repo": "swesmith/msiemens__tinydb.10644a0e", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "msiemens__tinydb.10644a0e.combine_file__0176isok", + "task_sha256": "b957581c5ef94a589b3af42f84e006aba32ce456f231edf0ddb838d690aaa96c", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "msiemens/tinydb", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/msiemens__tinydb.10644a0e", + "symlink_submodule_changes_supported": false, + "task_id": "msiemens__tinydb.10644a0e.combine_file__0176isok", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "msiemens/tinydb" +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/dependency-setup.sh b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..29ebee9df8beca1bfebc8b30cd7cb1dfc3cbf375 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/dependency-setup.sh @@ -0,0 +1,17 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +/usr/bin/sha256sum --check <<'OPENENV_NATIVE_TEST_REQUIREMENT' +4318e4525086b9ab07b2269c7a6f1ff2003ad01a663b94f56e772d63655166be pyproject.toml +OPENENV_NATIVE_TEST_REQUIREMENT +python -m pip install -e . +python -m pip install 'pytest>=7.2,<8' 'pytest-cov>=4,<5' + +cat > /tmp/openenv-tinydb-yaml.txt <<'OPENENV_PYYAML_PIN' +PyYAML==6.0.3 --hash=sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b +OPENENV_PYYAML_PIN +python -m pip install --no-deps --only-binary=:all: --require-hashes --index-url https://pypi.org/simple -r /tmp/openenv-tinydb-yaml.txt +python -c 'import yaml; assert yaml.__version__ == "6.0.3"' diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/environment/Dockerfile b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/instruction.md b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..796640809708b60b01dc7fd12c90d6d1f05bb80b --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/instruction.md @@ -0,0 +1,31 @@ +Database length returns incorrect value after operations + +#### Description + +The database length calculation is off by one, returning values that are one less than expected. This affects various database operations that rely on the length calculation. + +#### Steps/Code to Reproduce + +```python +from tinydb import TinyDB +from tinydb.storages import MemoryStorage + +# Create a new database and insert some documents +db = TinyDB(storage=MemoryStorage) +db.insert({'int': 1, 'char': 'a'}) +db.insert({'int': 1, 'char': 'b'}) +db.insert({'int': 1, 'char': 'c'}) + +# Check the length - should be 3 but returns 2 +print(f"Expected: 3, Got: {len(db)}") + +# This also affects operations like update counts +db.update({'int': 2}, lambda doc: doc['char'] == 'a') +print(f"Expected: 3, Got: {len(db)}") # Still returns 2 instead of 3 +``` + +The length should return the actual number of documents in the database, but it consistently returns a value that's one less than expected. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/metadata.json b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..31afcac0afa2f2b71c42eaf37a36e2de98ae2573 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/metadata.json @@ -0,0 +1,397 @@ +{ + "all_runtime_and_training_flags": false, + "checker_revision": { + "new_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "old_checker_sha256": "ce5f5ada4c63ab61c57177833687df68fcfe04df971699cb3e6ceada5722d2ed", + "old_plan_sha256": "6c91fe8ccbd5813aa1b13f310318d50d40222feb158abf0812d48856ff829d19", + "old_task_digest": "a6da42f8f9ca70d81a50034b0c52a9bca9032c3d6488792a1ebe6a0a6ed4b5e2", + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_grader_sha256": "48d05896ed5af21d9b8ab20e1b3470a370ab635d1c0c6ebf4e8851761c184532", + "runtime_qualified": false, + "source_tests_or_panels_changed": false, + "version": "matched-failure-precedence-v2" + }, + "official_profile": { + "eval_sets": [], + "profile_class": "Tinydb10644a0e", + "profile_lines": [ + 1020, + 1023 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "upstream_repo": "msiemens/tinydb" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_storages.py::test_yaml", + "tests/test_tinydb.py::test_drop_tables[memory]", + "tests/test_tinydb.py::test_drop_tables[json]", + "tests/test_tinydb.py::test_remove[memory]", + "tests/test_tinydb.py::test_remove[json]", + "tests/test_tinydb.py::test_remove_multiple[memory]", + "tests/test_tinydb.py::test_remove_multiple[json]", + "tests/test_tinydb.py::test_remove_ids[memory]", + "tests/test_tinydb.py::test_remove_ids[json]", + "tests/test_tinydb.py::test_update[memory]", + "tests/test_tinydb.py::test_update[json]", + "tests/test_tinydb.py::test_update_multiple[memory]", + "tests/test_tinydb.py::test_update_multiple[json]", + "tests/test_tinydb.py::test_upsert[memory]", + "tests/test_tinydb.py::test_upsert[json]", + "tests/test_tinydb.py::test_upsert_by_id[memory]", + "tests/test_tinydb.py::test_upsert_by_id[json]", + "tests/test_tinydb.py::test_multiple_dbs", + "tests/test_tinydb.py::test_unique_ids", + "tests/test_tinydb.py::test_doc_ids_json", + "tests/test_tinydb.py::test_drop_table", + "tests/test_tinydb.py::test_repr", + "tests/test_tinydb.py::test_empty_db_len", + "tests/test_tinydb.py::test_insert_on_existing_db" + ], + "PASS_TO_PASS": [ + "tests/test_middlewares.py::test_caching", + "tests/test_middlewares.py::test_caching_read", + "tests/test_middlewares.py::test_caching_write_many", + "tests/test_middlewares.py::test_caching_flush", + "tests/test_middlewares.py::test_caching_flush_manually", + "tests/test_middlewares.py::test_caching_write", + "tests/test_middlewares.py::test_nested", + "tests/test_middlewares.py::test_caching_json_write", + "tests/test_operations.py::test_delete[memory]", + "tests/test_operations.py::test_delete[json]", + "tests/test_operations.py::test_add_int[memory]", + "tests/test_operations.py::test_add_int[json]", + "tests/test_operations.py::test_add_str[memory]", + "tests/test_operations.py::test_add_str[json]", + "tests/test_operations.py::test_subtract[memory]", + "tests/test_operations.py::test_subtract[json]", + "tests/test_operations.py::test_set[memory]", + "tests/test_operations.py::test_set[json]", + "tests/test_operations.py::test_increment[memory]", + "tests/test_operations.py::test_increment[json]", + "tests/test_operations.py::test_decrement[memory]", + "tests/test_operations.py::test_decrement[json]", + "tests/test_queries.py::test_no_path", + "tests/test_queries.py::test_path_exists", + "tests/test_queries.py::test_path_and", + "tests/test_queries.py::test_callable_in_path_with_map", + "tests/test_queries.py::test_callable_in_path_with_chain", + "tests/test_queries.py::test_eq", + "tests/test_queries.py::test_ne", + "tests/test_queries.py::test_lt", + "tests/test_queries.py::test_le", + "tests/test_queries.py::test_gt", + "tests/test_queries.py::test_ge", + "tests/test_queries.py::test_or", + "tests/test_queries.py::test_and", + "tests/test_queries.py::test_not", + "tests/test_queries.py::test_has_key", + "tests/test_queries.py::test_regex", + "tests/test_queries.py::test_custom", + "tests/test_queries.py::test_custom_with_params", + "tests/test_queries.py::test_any", + "tests/test_queries.py::test_all", + "tests/test_queries.py::test_has", + "tests/test_queries.py::test_one_of", + "tests/test_queries.py::test_hash", + "tests/test_queries.py::test_orm_usage", + "tests/test_queries.py::test_repr", + "tests/test_queries.py::test_subclass", + "tests/test_queries.py::test_noop", + "tests/test_queries.py::test_equality", + "tests/test_queries.py::test_empty_query_error", + "tests/test_queries.py::test_fragment", + "tests/test_queries.py::test_fragment_with_path", + "tests/test_queries.py::test_get_item", + "tests/test_storages.py::test_json", + "tests/test_storages.py::test_json_kwargs", + "tests/test_storages.py::test_json_readwrite", + "tests/test_storages.py::test_json_read", + "tests/test_storages.py::test_create_dirs", + "tests/test_storages.py::test_json_invalid_directory", + "tests/test_storages.py::test_in_memory", + "tests/test_storages.py::test_in_memory_close", + "tests/test_storages.py::test_custom", + "tests/test_storages.py::test_read_once", + "tests/test_storages.py::test_custom_with_exception", + "tests/test_storages.py::test_encoding", + "tests/test_tables.py::test_next_id[memory]", + "tests/test_tables.py::test_next_id[json]", + "tests/test_tables.py::test_tables_list[memory]", + "tests/test_tables.py::test_tables_list[json]", + "tests/test_tables.py::test_one_table[memory]", + "tests/test_tables.py::test_one_table[json]", + "tests/test_tables.py::test_multiple_tables[memory]", + "tests/test_tables.py::test_multiple_tables[json]", + "tests/test_tables.py::test_caching[memory]", + "tests/test_tables.py::test_caching[json]", + "tests/test_tables.py::test_query_cache[memory]", + "tests/test_tables.py::test_query_cache[json]", + "tests/test_tables.py::test_query_cache_with_mutable_callable[memory]", + "tests/test_tables.py::test_query_cache_with_mutable_callable[json]", + "tests/test_tables.py::test_zero_cache_size[memory]", + "tests/test_tables.py::test_zero_cache_size[json]", + "tests/test_tables.py::test_query_cache_size[memory]", + "tests/test_tables.py::test_query_cache_size[json]", + "tests/test_tables.py::test_lru_cache[memory]", + "tests/test_tables.py::test_lru_cache[json]", + "tests/test_tables.py::test_table_is_iterable[memory]", + "tests/test_tables.py::test_table_is_iterable[json]", + "tests/test_tables.py::test_table_name[memory]", + "tests/test_tables.py::test_table_name[json]", + "tests/test_tables.py::test_table_repr[memory]", + "tests/test_tables.py::test_table_repr[json]", + "tests/test_tables.py::test_truncate_table[memory]", + "tests/test_tables.py::test_truncate_table[json]", + "tests/test_tables.py::test_persist_table[memory]", + "tests/test_tables.py::test_persist_table[json]", + "tests/test_tinydb.py::test_all[memory]", + "tests/test_tinydb.py::test_all[json]", + "tests/test_tinydb.py::test_insert[memory]", + "tests/test_tinydb.py::test_insert[json]", + "tests/test_tinydb.py::test_insert_ids[memory]", + "tests/test_tinydb.py::test_insert_ids[json]", + "tests/test_tinydb.py::test_insert_with_doc_id[memory]", + "tests/test_tinydb.py::test_insert_with_doc_id[json]", + "tests/test_tinydb.py::test_insert_with_duplicate_doc_id[memory]", + "tests/test_tinydb.py::test_insert_with_duplicate_doc_id[json]", + "tests/test_tinydb.py::test_insert_multiple[memory]", + "tests/test_tinydb.py::test_insert_multiple[json]", + "tests/test_tinydb.py::test_insert_multiple_with_ids[memory]", + "tests/test_tinydb.py::test_insert_multiple_with_ids[json]", + "tests/test_tinydb.py::test_insert_multiple_with_doc_ids[memory]", + "tests/test_tinydb.py::test_insert_multiple_with_doc_ids[json]", + "tests/test_tinydb.py::test_insert_invalid_type_raises_error[memory]", + "tests/test_tinydb.py::test_insert_invalid_type_raises_error[json]", + "tests/test_tinydb.py::test_insert_valid_mapping_type[memory]", + "tests/test_tinydb.py::test_insert_valid_mapping_type[json]", + "tests/test_tinydb.py::test_custom_mapping_type_with_json", + "tests/test_tinydb.py::test_remove_all_fails[memory]", + "tests/test_tinydb.py::test_remove_all_fails[json]", + "tests/test_tinydb.py::test_remove_returns_ids[memory]", + "tests/test_tinydb.py::test_remove_returns_ids[json]", + "tests/test_tinydb.py::test_update_all[memory]", + "tests/test_tinydb.py::test_update_all[json]", + "tests/test_tinydb.py::test_update_returns_ids[memory]", + "tests/test_tinydb.py::test_update_returns_ids[json]", + "tests/test_tinydb.py::test_update_transform[memory]", + "tests/test_tinydb.py::test_update_transform[json]", + "tests/test_tinydb.py::test_update_ids[memory]", + "tests/test_tinydb.py::test_update_ids[json]", + "tests/test_tinydb.py::test_update_multiple_operation[memory]", + "tests/test_tinydb.py::test_update_multiple_operation[json]", + "tests/test_tinydb.py::test_search[memory]", + "tests/test_tinydb.py::test_search[json]", + "tests/test_tinydb.py::test_search_path[memory]", + "tests/test_tinydb.py::test_search_path[json]", + "tests/test_tinydb.py::test_search_no_results_cache[memory]", + "tests/test_tinydb.py::test_search_no_results_cache[json]", + "tests/test_tinydb.py::test_get[memory]", + "tests/test_tinydb.py::test_get[json]", + "tests/test_tinydb.py::test_get_ids[memory]", + "tests/test_tinydb.py::test_get_ids[json]", + "tests/test_tinydb.py::test_get_multiple_ids[memory]", + "tests/test_tinydb.py::test_get_multiple_ids[json]", + "tests/test_tinydb.py::test_get_invalid[memory]", + "tests/test_tinydb.py::test_get_invalid[json]", + "tests/test_tinydb.py::test_count[memory]", + "tests/test_tinydb.py::test_count[json]", + "tests/test_tinydb.py::test_contains[memory]", + "tests/test_tinydb.py::test_contains[json]", + "tests/test_tinydb.py::test_contains_ids[memory]", + "tests/test_tinydb.py::test_contains_ids[json]", + "tests/test_tinydb.py::test_contains_invalid[memory]", + "tests/test_tinydb.py::test_contains_invalid[json]", + "tests/test_tinydb.py::test_get_idempotent[memory]", + "tests/test_tinydb.py::test_get_idempotent[json]", + "tests/test_tinydb.py::test_storage_closed_once", + "tests/test_tinydb.py::test_lastid_after_open", + "tests/test_tinydb.py::test_insert_string", + "tests/test_tinydb.py::test_insert_invalid_dict", + "tests/test_tinydb.py::test_gc", + "tests/test_tinydb.py::test_empty_write", + "tests/test_tinydb.py::test_query_cache", + "tests/test_tinydb.py::test_tinydb_is_iterable[memory]", + "tests/test_tinydb.py::test_tinydb_is_iterable[json]", + "tests/test_tinydb.py::test_delete", + "tests/test_tinydb.py::test_insert_multiple_with_single_dict[memory]", + "tests/test_tinydb.py::test_insert_multiple_with_single_dict[json]", + "tests/test_tinydb.py::test_access_storage", + "tests/test_tinydb.py::test_storage_access", + "tests/test_tinydb.py::test_lambda_query", + "tests/test_utils.py::test_lru_cache", + "tests/test_utils.py::test_lru_cache_set_multiple", + "tests/test_utils.py::test_lru_cache_set_update", + "tests/test_utils.py::test_lru_cache_get", + "tests/test_utils.py::test_lru_cache_delete", + "tests/test_utils.py::test_lru_cache_clear", + "tests/test_utils.py::test_lru_cache_unlimited", + "tests/test_utils.py::test_lru_cache_unlimited_explicit", + "tests/test_utils.py::test_lru_cache_iteration_works", + "tests/test_utils.py::test_freeze" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "a603f16b47d665761852fbe708c19b0c071cd1e8", + "healthy": "278700580526dd378f18f40b641885ec78df63e1", + "learner": "325398e5f584172582480e327ab123a2b58c240b" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.github/stale.yml", + "/testbed/.gitignore", + "/testbed/.readthedocs.yml", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/artwork/logo.png", + "/testbed/artwork/logo.svg", + "/testbed/docs/.gitignore", + "/testbed/docs/Makefile", + "/testbed/docs/_static/logo.png", + "/testbed/docs/_templates/links.html", + "/testbed/docs/_templates/sidebarlogo.html", + "/testbed/docs/_themes/.gitignore", + "/testbed/docs/_themes/LICENSE", + "/testbed/docs/_themes/README", + "/testbed/docs/_themes/flask/layout.html", + "/testbed/docs/_themes/flask/page.html", + "/testbed/docs/_themes/flask/relations.html", + "/testbed/docs/_themes/flask/static/flasky.css_t", + "/testbed/docs/_themes/flask/theme.conf", + "/testbed/docs/_themes/flask_theme_support.py", + "/testbed/docs/api.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contribute.rst", + "/testbed/docs/extend.rst", + "/testbed/docs/extensions.rst", + "/testbed/docs/getting-started.rst", + "/testbed/docs/index.rst", + "/testbed/docs/intro.rst", + "/testbed/docs/make.bat", + "/testbed/docs/upgrade.rst", + "/testbed/docs/usage.rst", + "/testbed/mypy.ini", + "/testbed/poetry.lock", + "/testbed/pyproject.toml", + "/testbed/pytest.ini", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/test_middlewares.py", + "/testbed/tests/test_operations.py", + "/testbed/tests/test_queries.py", + "/testbed/tests/test_tables.py", + "/testbed/tests/test_utils.py", + "/testbed/tinydb/__init__.py", + "/testbed/tinydb/database.py", + "/testbed/tinydb/middlewares.py", + "/testbed/tinydb/mypy_plugin.py", + "/testbed/tinydb/operations.py", + "/testbed/tinydb/py.typed", + "/testbed/tinydb/queries.py", + "/testbed/tinydb/storages.py", + "/testbed/tinydb/table.py", + "/testbed/tinydb/utils.py", + "/testbed/tinydb/version.py" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Tinydb10644a0e", + "profile_lines": [ + 1020, + 1023 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "upstream_repo": "msiemens/tinydb" + }, + "original_source_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "private_test_paths": [ + "tests/test_storages.py", + "tests/test_tinydb.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "tinydb/database.py" + ], + "source_repo": "swesmith/msiemens__tinydb.10644a0e", + "source_stages_bytes": 933018, + "task_id": "msiemens__tinydb.10644a0e.combine_file__0176isok", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "msiemens/tinydb" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:msiemens__tinydb.10644a0e.combine_file__0176isok", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "278700580526dd378f18f40b641885ec78df63e1", + "instruction_sha256": "e72ed6224bacc52f43645133460f4ba0c52c5e1f6f57086f536ee6003cbfd02f", + "is_fork": true, + "learner_path": "tasks/4feabf9a847b20ba0e24109c/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "actual_upstream_url": "https://raw.githubusercontent.com/msiemens/tinydb/10644a0e07ad180c5b756aba272ee6b0dbd12df8/LICENSE", + "reviewed": true, + "sha256": "b0e2a2d39271e3d96b717d7be8235ac413d74797bf7f742f0801cfaad6c8c912", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/msiemens__tinydb.10644a0e/325398e5f584172582480e327ab123a2b58c240b/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "patch_sha256": "74761a8f574379f7758dbd1d8366749758357275c15c27c2e41083ca595ad8ae", + "provenance_path": "tasks/4feabf9a847b20ba0e24109c/source-proof.json", + "repository_lineage": [ + "swesmith/msiemens__tinydb.10644a0e", + "msiemens/tinydb" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "325398e5f584172582480e327ab123a2b58c240b", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "a603f16b47d665761852fbe708c19b0c071cd1e8", + "source_kind": "mutation", + "source_repo": "swesmith/msiemens__tinydb.10644a0e", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "msiemens__tinydb.10644a0e.combine_file__0176isok", + "task_sha256": "b957581c5ef94a589b3af42f84e006aba32ce456f231edf0ddb838d690aaa96c", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "msiemens/tinydb", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/provenance.json b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..a17e32fd7e13031e4fe991013050bf644129e89c --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "d7be2fd072b6b80aa3e760a4c6a32d707cd60939d30851b646240b08d23c8b07", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "actual_upstream_url": "https://raw.githubusercontent.com/msiemens/tinydb/10644a0e07ad180c5b756aba272ee6b0dbd12df8/LICENSE", + "reviewed": true, + "sha256": "b0e2a2d39271e3d96b717d7be8235ac413d74797bf7f742f0801cfaad6c8c912", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/msiemens__tinydb.10644a0e/325398e5f584172582480e327ab123a2b58c240b/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "cca3cc73a00b1bb6d2823bb46523b9eac58f0538fa95799bb542248190685ffe", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "f03dff0b5918fc86c79bf1a753d64d4d7b2697d71155e13dc4a0f35116c1bf07", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:msiemens__tinydb.10644a0e.combine_file__0176isok", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "278700580526dd378f18f40b641885ec78df63e1", + "instruction_sha256": "e72ed6224bacc52f43645133460f4ba0c52c5e1f6f57086f536ee6003cbfd02f", + "is_fork": true, + "learner_path": "tasks/4feabf9a847b20ba0e24109c/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "actual_upstream_url": "https://raw.githubusercontent.com/msiemens/tinydb/10644a0e07ad180c5b756aba272ee6b0dbd12df8/LICENSE", + "reviewed": true, + "sha256": "b0e2a2d39271e3d96b717d7be8235ac413d74797bf7f742f0801cfaad6c8c912", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/msiemens__tinydb.10644a0e/325398e5f584172582480e327ab123a2b58c240b/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "patch_sha256": "74761a8f574379f7758dbd1d8366749758357275c15c27c2e41083ca595ad8ae", + "provenance_path": "tasks/4feabf9a847b20ba0e24109c/source-proof.json", + "repository_lineage": [ + "swesmith/msiemens__tinydb.10644a0e", + "msiemens/tinydb" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "325398e5f584172582480e327ab123a2b58c240b", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "a603f16b47d665761852fbe708c19b0c071cd1e8", + "source_kind": "mutation", + "source_repo": "swesmith/msiemens__tinydb.10644a0e", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "msiemens__tinydb.10644a0e.combine_file__0176isok", + "task_sha256": "b957581c5ef94a589b3af42f84e006aba32ce456f231edf0ddb838d690aaa96c", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "msiemens/tinydb", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "ff9a5ef814fab3aeaea8a510213b4330c9b7600d0e4cd9f29754ec6179c0d458" +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/provided-gold.diff b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..ca0d3debc4a3be7208cefcff8f9a16ce12c0363c --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/provided-gold.diff @@ -0,0 +1,45 @@ +diff --git a/tinydb/database.py b/tinydb/database.py +index 3b36269d02892e833fc23e75cb089a32ec1d2533..4a73c466f639b166c3a51f7544ce4e81a1e5e5b4 100644 +--- a/tinydb/database.py ++++ b/tinydb/database.py +@@ -180,22 +180,25 @@ + :param name: The name of the table to drop. + """ + ++ # If the table is currently opened, we need to forget the table class ++ # instance + if name in self._tables: + del self._tables[name] + + data = self.storage.read() + ++ # The database is uninitialized, there's nothing to do + if data is None: + return + +- # The logic of checking table existence is altered +- if name in data: ++ # The table does not exist, there's nothing to do ++ if name not in data: + return + +- # Incorrectly skip removing table data +- del data +- +- # Incorrectly write the unmodified data back to the storage ++ # Remove the table from the data dict ++ del data[name] ++ ++ # Store the updated data back to the storage + self.storage.write(data) + + @property +@@ -262,7 +265,7 @@ + >>> len(db) + 0 + """ +- return len(self.table(self.default_table_name)) - 1 ++ return len(self.table(self.default_table_name)) + + def __iter__(self) -> Iterator[Document]: + """ diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/solution/solve.sh b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..51dbd6b5ca0f0cccddee3ff6fbc104ff677e9175 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/solution/solve.sh @@ -0,0 +1,51 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/tinydb/database.py b/tinydb/database.py +index 3b36269d02892e833fc23e75cb089a32ec1d2533..4a73c466f639b166c3a51f7544ce4e81a1e5e5b4 100644 +--- a/tinydb/database.py ++++ b/tinydb/database.py +@@ -180,22 +180,25 @@ + :param name: The name of the table to drop. + """ + ++ # If the table is currently opened, we need to forget the table class ++ # instance + if name in self._tables: + del self._tables[name] + + data = self.storage.read() + ++ # The database is uninitialized, there's nothing to do + if data is None: + return + +- # The logic of checking table existence is altered +- if name in data: ++ # The table does not exist, there's nothing to do ++ if name not in data: + return + +- # Incorrectly skip removing table data +- del data +- +- # Incorrectly write the unmodified data back to the storage ++ # Remove the table from the data dict ++ del data[name] ++ ++ # Store the updated data back to the storage + self.storage.write(data) + + @property +@@ -262,7 +265,7 @@ + >>> len(db) + 0 + """ +- return len(self.table(self.default_table_name)) - 1 ++ return len(self.table(self.default_table_name)) + + def __iter__(self) -> Iterator[Document]: + """ +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/task.toml b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b8193e2a4e8aa8bfc8f59f17142e94a72d61c383 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:1dbde4df3b81e9632e8d8599b49ac92db266a9f51060a1eb5f155ee7e80610ae" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/check_pytest.py b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/expected-panels.json b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..b43cd00ac68032270f420c81af1c0e73177c4c39 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/expected-panels.json @@ -0,0 +1,210 @@ +{ + "fail-to-pass": [ + "tests/test_storages.py::test_yaml", + "tests/test_tinydb.py::test_drop_tables[memory]", + "tests/test_tinydb.py::test_drop_tables[json]", + "tests/test_tinydb.py::test_remove[memory]", + "tests/test_tinydb.py::test_remove[json]", + "tests/test_tinydb.py::test_remove_multiple[memory]", + "tests/test_tinydb.py::test_remove_multiple[json]", + "tests/test_tinydb.py::test_remove_ids[memory]", + "tests/test_tinydb.py::test_remove_ids[json]", + "tests/test_tinydb.py::test_update[memory]", + "tests/test_tinydb.py::test_update[json]", + "tests/test_tinydb.py::test_update_multiple[memory]", + "tests/test_tinydb.py::test_update_multiple[json]", + "tests/test_tinydb.py::test_upsert[memory]", + "tests/test_tinydb.py::test_upsert[json]", + "tests/test_tinydb.py::test_upsert_by_id[memory]", + "tests/test_tinydb.py::test_upsert_by_id[json]", + "tests/test_tinydb.py::test_multiple_dbs", + "tests/test_tinydb.py::test_unique_ids", + "tests/test_tinydb.py::test_doc_ids_json", + "tests/test_tinydb.py::test_drop_table", + "tests/test_tinydb.py::test_repr", + "tests/test_tinydb.py::test_empty_db_len", + "tests/test_tinydb.py::test_insert_on_existing_db" + ], + "pass-to-pass": [ + "tests/test_middlewares.py::test_caching", + "tests/test_middlewares.py::test_caching_read", + "tests/test_middlewares.py::test_caching_write_many", + "tests/test_middlewares.py::test_caching_flush", + "tests/test_middlewares.py::test_caching_flush_manually", + "tests/test_middlewares.py::test_caching_write", + "tests/test_middlewares.py::test_nested", + "tests/test_middlewares.py::test_caching_json_write", + "tests/test_operations.py::test_delete[memory]", + "tests/test_operations.py::test_delete[json]", + "tests/test_operations.py::test_add_int[memory]", + "tests/test_operations.py::test_add_int[json]", + "tests/test_operations.py::test_add_str[memory]", + "tests/test_operations.py::test_add_str[json]", + "tests/test_operations.py::test_subtract[memory]", + "tests/test_operations.py::test_subtract[json]", + "tests/test_operations.py::test_set[memory]", + "tests/test_operations.py::test_set[json]", + "tests/test_operations.py::test_increment[memory]", + "tests/test_operations.py::test_increment[json]", + "tests/test_operations.py::test_decrement[memory]", + "tests/test_operations.py::test_decrement[json]", + "tests/test_queries.py::test_no_path", + "tests/test_queries.py::test_path_exists", + "tests/test_queries.py::test_path_and", + "tests/test_queries.py::test_callable_in_path_with_map", + "tests/test_queries.py::test_callable_in_path_with_chain", + "tests/test_queries.py::test_eq", + "tests/test_queries.py::test_ne", + "tests/test_queries.py::test_lt", + "tests/test_queries.py::test_le", + "tests/test_queries.py::test_gt", + "tests/test_queries.py::test_ge", + "tests/test_queries.py::test_or", + "tests/test_queries.py::test_and", + "tests/test_queries.py::test_not", + "tests/test_queries.py::test_has_key", + "tests/test_queries.py::test_regex", + "tests/test_queries.py::test_custom", + "tests/test_queries.py::test_custom_with_params", + "tests/test_queries.py::test_any", + "tests/test_queries.py::test_all", + "tests/test_queries.py::test_has", + "tests/test_queries.py::test_one_of", + "tests/test_queries.py::test_hash", + "tests/test_queries.py::test_orm_usage", + "tests/test_queries.py::test_repr", + "tests/test_queries.py::test_subclass", + "tests/test_queries.py::test_noop", + "tests/test_queries.py::test_equality", + "tests/test_queries.py::test_empty_query_error", + "tests/test_queries.py::test_fragment", + "tests/test_queries.py::test_fragment_with_path", + "tests/test_queries.py::test_get_item", + "tests/test_storages.py::test_json", + "tests/test_storages.py::test_json_kwargs", + "tests/test_storages.py::test_json_readwrite", + "tests/test_storages.py::test_json_read", + "tests/test_storages.py::test_create_dirs", + "tests/test_storages.py::test_json_invalid_directory", + "tests/test_storages.py::test_in_memory", + "tests/test_storages.py::test_in_memory_close", + "tests/test_storages.py::test_custom", + "tests/test_storages.py::test_read_once", + "tests/test_storages.py::test_custom_with_exception", + "tests/test_storages.py::test_encoding", + "tests/test_tables.py::test_next_id[memory]", + "tests/test_tables.py::test_next_id[json]", + "tests/test_tables.py::test_tables_list[memory]", + "tests/test_tables.py::test_tables_list[json]", + "tests/test_tables.py::test_one_table[memory]", + "tests/test_tables.py::test_one_table[json]", + "tests/test_tables.py::test_multiple_tables[memory]", + "tests/test_tables.py::test_multiple_tables[json]", + "tests/test_tables.py::test_caching[memory]", + "tests/test_tables.py::test_caching[json]", + "tests/test_tables.py::test_query_cache[memory]", + "tests/test_tables.py::test_query_cache[json]", + "tests/test_tables.py::test_query_cache_with_mutable_callable[memory]", + "tests/test_tables.py::test_query_cache_with_mutable_callable[json]", + "tests/test_tables.py::test_zero_cache_size[memory]", + "tests/test_tables.py::test_zero_cache_size[json]", + "tests/test_tables.py::test_query_cache_size[memory]", + "tests/test_tables.py::test_query_cache_size[json]", + "tests/test_tables.py::test_lru_cache[memory]", + "tests/test_tables.py::test_lru_cache[json]", + "tests/test_tables.py::test_table_is_iterable[memory]", + "tests/test_tables.py::test_table_is_iterable[json]", + "tests/test_tables.py::test_table_name[memory]", + "tests/test_tables.py::test_table_name[json]", + "tests/test_tables.py::test_table_repr[memory]", + "tests/test_tables.py::test_table_repr[json]", + "tests/test_tables.py::test_truncate_table[memory]", + "tests/test_tables.py::test_truncate_table[json]", + "tests/test_tables.py::test_persist_table[memory]", + "tests/test_tables.py::test_persist_table[json]", + "tests/test_tinydb.py::test_all[memory]", + "tests/test_tinydb.py::test_all[json]", + "tests/test_tinydb.py::test_insert[memory]", + "tests/test_tinydb.py::test_insert[json]", + "tests/test_tinydb.py::test_insert_ids[memory]", + "tests/test_tinydb.py::test_insert_ids[json]", + "tests/test_tinydb.py::test_insert_with_doc_id[memory]", + "tests/test_tinydb.py::test_insert_with_doc_id[json]", + "tests/test_tinydb.py::test_insert_with_duplicate_doc_id[memory]", + "tests/test_tinydb.py::test_insert_with_duplicate_doc_id[json]", + "tests/test_tinydb.py::test_insert_multiple[memory]", + "tests/test_tinydb.py::test_insert_multiple[json]", + "tests/test_tinydb.py::test_insert_multiple_with_ids[memory]", + "tests/test_tinydb.py::test_insert_multiple_with_ids[json]", + "tests/test_tinydb.py::test_insert_multiple_with_doc_ids[memory]", + "tests/test_tinydb.py::test_insert_multiple_with_doc_ids[json]", + "tests/test_tinydb.py::test_insert_invalid_type_raises_error[memory]", + "tests/test_tinydb.py::test_insert_invalid_type_raises_error[json]", + "tests/test_tinydb.py::test_insert_valid_mapping_type[memory]", + "tests/test_tinydb.py::test_insert_valid_mapping_type[json]", + "tests/test_tinydb.py::test_custom_mapping_type_with_json", + "tests/test_tinydb.py::test_remove_all_fails[memory]", + "tests/test_tinydb.py::test_remove_all_fails[json]", + "tests/test_tinydb.py::test_remove_returns_ids[memory]", + "tests/test_tinydb.py::test_remove_returns_ids[json]", + "tests/test_tinydb.py::test_update_all[memory]", + "tests/test_tinydb.py::test_update_all[json]", + "tests/test_tinydb.py::test_update_returns_ids[memory]", + "tests/test_tinydb.py::test_update_returns_ids[json]", + "tests/test_tinydb.py::test_update_transform[memory]", + "tests/test_tinydb.py::test_update_transform[json]", + "tests/test_tinydb.py::test_update_ids[memory]", + "tests/test_tinydb.py::test_update_ids[json]", + "tests/test_tinydb.py::test_update_multiple_operation[memory]", + "tests/test_tinydb.py::test_update_multiple_operation[json]", + "tests/test_tinydb.py::test_search[memory]", + "tests/test_tinydb.py::test_search[json]", + "tests/test_tinydb.py::test_search_path[memory]", + "tests/test_tinydb.py::test_search_path[json]", + "tests/test_tinydb.py::test_search_no_results_cache[memory]", + "tests/test_tinydb.py::test_search_no_results_cache[json]", + "tests/test_tinydb.py::test_get[memory]", + "tests/test_tinydb.py::test_get[json]", + "tests/test_tinydb.py::test_get_ids[memory]", + "tests/test_tinydb.py::test_get_ids[json]", + "tests/test_tinydb.py::test_get_multiple_ids[memory]", + "tests/test_tinydb.py::test_get_multiple_ids[json]", + "tests/test_tinydb.py::test_get_invalid[memory]", + "tests/test_tinydb.py::test_get_invalid[json]", + "tests/test_tinydb.py::test_count[memory]", + "tests/test_tinydb.py::test_count[json]", + "tests/test_tinydb.py::test_contains[memory]", + "tests/test_tinydb.py::test_contains[json]", + "tests/test_tinydb.py::test_contains_ids[memory]", + "tests/test_tinydb.py::test_contains_ids[json]", + "tests/test_tinydb.py::test_contains_invalid[memory]", + "tests/test_tinydb.py::test_contains_invalid[json]", + "tests/test_tinydb.py::test_get_idempotent[memory]", + "tests/test_tinydb.py::test_get_idempotent[json]", + "tests/test_tinydb.py::test_storage_closed_once", + "tests/test_tinydb.py::test_lastid_after_open", + "tests/test_tinydb.py::test_insert_string", + "tests/test_tinydb.py::test_insert_invalid_dict", + "tests/test_tinydb.py::test_gc", + "tests/test_tinydb.py::test_empty_write", + "tests/test_tinydb.py::test_query_cache", + "tests/test_tinydb.py::test_tinydb_is_iterable[memory]", + "tests/test_tinydb.py::test_tinydb_is_iterable[json]", + "tests/test_tinydb.py::test_delete", + "tests/test_tinydb.py::test_insert_multiple_with_single_dict[memory]", + "tests/test_tinydb.py::test_insert_multiple_with_single_dict[json]", + "tests/test_tinydb.py::test_access_storage", + "tests/test_tinydb.py::test_storage_access", + "tests/test_tinydb.py::test_lambda_query", + "tests/test_utils.py::test_lru_cache", + "tests/test_utils.py::test_lru_cache_set_multiple", + "tests/test_utils.py::test_lru_cache_set_update", + "tests/test_utils.py::test_lru_cache_get", + "tests/test_utils.py::test_lru_cache_delete", + "tests/test_utils.py::test_lru_cache_clear", + "tests/test_utils.py::test_lru_cache_unlimited", + "tests/test_utils.py::test_lru_cache_unlimited_explicit", + "tests/test_utils.py::test_lru_cache_iteration_works", + "tests/test_utils.py::test_freeze" + ] +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/grade.py b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/panel-config.json b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..d9314376e51e1a2b862751e17bcc1da621853309 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install 'pytest>=7.2,<8' 'pytest-cov>=4,<5'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4318e4525086b9ab07b2269c7a6f1ff2003ad01a663b94f56e772d63655166be", + "pytest.ini": "2c2ccbf97dabef288fd402c4bb1ddba4d3baa35d1f903a3f5735633c1d504b7c" + } +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/test.sh b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted-inventory.json b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..e3f7747a66be371780111d5bf493d9b1ca6fe41b --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted-inventory.json @@ -0,0 +1,62 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 1846, + "mode": 420, + "sha256": "4318e4525086b9ab07b2269c7a6f1ff2003ad01a663b94f56e772d63655166be" + }, + "pytest.ini": { + "bytes": 70, + "mode": 420, + "sha256": "2c2ccbf97dabef288fd402c4bb1ddba4d3baa35d1f903a3f5735633c1d504b7c" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 625, + "mode": 420, + "sha256": "502596fae1843322ec533028a76474d39e6fb70587a5749d8c9dd734b35e625b" + }, + "tests/test_middlewares.py": { + "bytes": 2412, + "mode": 420, + "sha256": "85a748d3d10e7be042ed37318153a6b79c7913a5d9536cad406ccccad380577b" + }, + "tests/test_operations.py": { + "bytes": 1021, + "mode": 420, + "sha256": "6313d342626a12973a5532b0b9344c5a30a959d7bfa4f6ca07d147317aee469e" + }, + "tests/test_queries.py": { + "bytes": 12331, + "mode": 420, + "sha256": "7978c6220a192f4256018bf37d76e6b4c644a962fed4d6fca7d8594b2cf63a49" + }, + "tests/test_storages.py": { + "bytes": 6489, + "mode": 420, + "sha256": "d74695d20e1d1742fa558da49bc2df8e84ca34e64e001070cbccce215bd39fa2" + }, + "tests/test_tables.py": { + "bytes": 4109, + "mode": 420, + "sha256": "f018615899e7c9c813aba0820c639f9402d3c9865a376eedaf9dc3ee89b85ef3" + }, + "tests/test_tinydb.py": { + "bytes": 18110, + "mode": 420, + "sha256": "d106d5e94536afe8416c1b8b01bc63381abb97f81a6a120743e7e1963b07b1d1" + }, + "tests/test_utils.py": { + "bytes": 2257, + "mode": 420, + "sha256": "659bd414226988e81d2811259c112676aa6bdfa3b9fb6fed4631030ae6d73f2e" + } + } +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/pyproject.toml b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..1cd4da1e6719a2d3895c33b51dab148a4b60dde3 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/pyproject.toml @@ -0,0 +1,61 @@ +[tool.poetry] +name = "tinydb" +version = "4.8.2" +description = "TinyDB is a tiny, document oriented database optimized for your happiness :)" +authors = ["Markus Siemens "] +license = "MIT" + +readme = "README.rst" + +homepage = "https://github.com/msiemens/tinydb" +documentation = "https://tinydb.readthedocs.org/" + +keywords = ["database", "nosql"] + +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Intended Audience :: System Administrators", + "License :: OSI Approved :: MIT License", + "Topic :: Database", + "Topic :: Database :: Database Engines/Servers", + "Topic :: Utilities", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Operating System :: OS Independent", + "Typing :: Typed", +] + +packages = [ + { include = "tinydb" }, + { include = "tests", format = "sdist" } +] + +[tool.poetry.urls] +"Changelog" = "https://tinydb.readthedocs.io/en/latest/changelog.html" +"Issues" = "https://github.com/msiemens/tinydb/issues" + +[tool.poetry.dependencies] +python = "^3.8" + +[tool.poetry.dev-dependencies] +pytest = "^7.2.0" +pytest-pycodestyle = "^2.3.1" +pytest-cov = "^4.0.0" +pycodestyle = "^2.10.0" +sphinx = "^7.0.0" +coveralls = "^3.3.1" +pyyaml = "^6.0" +pytest-mypy = { version = "^0.10.2", markers = "platform_python_implementation != 'PyPy'" } +types-PyYAML = "^6.0.0" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/pytest.ini b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..45e8707db03d886e6ec161802ec3d96694a4a5a7 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +addopts=--verbose --cov-append --cov-report term --cov tinydb \ No newline at end of file diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/__init__.py b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/conftest.py b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..99c3eaf2505aa0da13eee34d9e0f664d9a2c8b0e --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +import os.path +import tempfile +from pathlib import Path + +import pytest # type: ignore + +from tinydb.middlewares import CachingMiddleware +from tinydb.storages import MemoryStorage +from tinydb import TinyDB, JSONStorage + + +@pytest.fixture(params=['memory', 'json']) +def db(request, tmp_path: Path): + if request.param == 'json': + db_ = TinyDB(tmp_path / 'test.db', storage=JSONStorage) + else: + db_ = TinyDB(storage=MemoryStorage) + + db_.drop_tables() + db_.insert_multiple({'int': 1, 'char': c} for c in 'abc') + + yield db_ + + +@pytest.fixture +def storage(): + return CachingMiddleware(MemoryStorage)() diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_middlewares.py b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_middlewares.py new file mode 100644 index 0000000000000000000000000000000000000000..81a211950d37ae25078fdddb97381c9d7385fad8 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_middlewares.py @@ -0,0 +1,105 @@ +import os + +from tinydb import TinyDB +from tinydb.middlewares import CachingMiddleware +from tinydb.storages import MemoryStorage, JSONStorage + +doc = {'none': [None, None], 'int': 42, 'float': 3.1415899999999999, + 'list': ['LITE', 'RES_ACID', 'SUS_DEXT'], + 'dict': {'hp': 13, 'sp': 5}, + 'bool': [True, False, True, False]} + + +def test_caching(storage): + # Write contents + storage.write(doc) + + # Verify contents + assert doc == storage.read() + + +def test_caching_read(): + db = TinyDB(storage=CachingMiddleware(MemoryStorage)) + assert db.all() == [] + + +def test_caching_write_many(storage): + storage.WRITE_CACHE_SIZE = 3 + + # Storage should be still empty + assert storage.memory is None + + # Write contents + for x in range(2): + storage.write(doc) + assert storage.memory is None # Still cached + + storage.write(doc) + + # Verify contents: Cache should be emptied and written to storage + assert storage.memory + + +def test_caching_flush(storage): + # Write contents + for _ in range(CachingMiddleware.WRITE_CACHE_SIZE - 1): + storage.write(doc) + + # Not yet flushed... + assert storage.memory is None + + storage.write(doc) + + # Verify contents: Cache should be emptied and written to storage + assert storage.memory + + +def test_caching_flush_manually(storage): + # Write contents + storage.write(doc) + + storage.flush() + + # Verify contents: Cache should be emptied and written to storage + assert storage.memory + + +def test_caching_write(storage): + # Write contents + storage.write(doc) + + storage.close() + + # Verify contents: Cache should be emptied and written to storage + assert storage.storage.memory + + +def test_nested(): + storage = CachingMiddleware(MemoryStorage) + storage() # Initialization + + # Write contents + storage.write(doc) + + # Verify contents + assert doc == storage.read() + + +def test_caching_json_write(tmpdir): + path = str(tmpdir.join('test.db')) + + with TinyDB(path, storage=CachingMiddleware(JSONStorage)) as db: + db.insert({'key': 'value'}) + + # Verify database filesize + statinfo = os.stat(path) + assert statinfo.st_size != 0 + + # Assert JSON file has been closed + assert db._storage._handle.closed + + del db + + # Reopen database + with TinyDB(path, storage=CachingMiddleware(JSONStorage)) as db: + assert db.all() == [{'key': 'value'}] diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_operations.py b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6f814f6ac61cea8684c373a413ff5aa9f7ae0c --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_operations.py @@ -0,0 +1,37 @@ +from tinydb import where +from tinydb.operations import delete, increment, decrement, add, subtract, set + + +def test_delete(db): + db.update(delete('int'), where('char') == 'a') + assert 'int' not in db.get(where('char') == 'a') + + +def test_add_int(db): + db.update(add('int', 5), where('char') == 'a') + assert db.get(where('char') == 'a')['int'] == 6 + + +def test_add_str(db): + db.update(add('char', 'xyz'), where('char') == 'a') + assert db.get(where('char') == 'axyz')['int'] == 1 + + +def test_subtract(db): + db.update(subtract('int', 5), where('char') == 'a') + assert db.get(where('char') == 'a')['int'] == -4 + + +def test_set(db): + db.update(set('char', 'xyz'), where('char') == 'a') + assert db.get(where('char') == 'xyz')['int'] == 1 + + +def test_increment(db): + db.update(increment('int'), where('char') == 'a') + assert db.get(where('char') == 'a')['int'] == 2 + + +def test_decrement(db): + db.update(decrement('int'), where('char') == 'a') + assert db.get(where('char') == 'a')['int'] == 0 diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_queries.py b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_queries.py new file mode 100644 index 0000000000000000000000000000000000000000..6e0dd8faa974a01cc23722c5d0d316a7d0a37193 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_queries.py @@ -0,0 +1,445 @@ +import re + +import pytest + +from tinydb.queries import Query, where + + +def test_no_path(): + with pytest.raises(ValueError): + _ = Query() == 2 + + +def test_path_exists(): + query = Query()['value'].exists() + assert query == where('value').exists() + assert query({'value': 1}) + assert not query({'something': 1}) + assert hash(query) + assert hash(query) != hash(where('asd')) + + query = Query()['value']['val'].exists() + assert query == where('value')['val'].exists() + assert query({'value': {'val': 2}}) + assert not query({'value': 1}) + assert not query({'value': {'asd': 1}}) + assert not query({'something': 1}) + assert hash(query) + assert hash(query) != hash(where('asd')) + + +def test_path_and(): + query = Query()['value'].exists() & (Query()['value'] == 5) + assert query({'value': 5}) + assert not query({'value': 10}) + assert not query({'something': 1}) + assert hash(query) + assert hash(query) != hash(where('value')) + + +def test_callable_in_path_with_map(): + double = lambda x: x + x + query = Query().value.map(double) == 10 + assert query({'value': 5}) + assert not query({'value': 10}) + + +def test_callable_in_path_with_chain(): + rekey = lambda x: {'y': x['a'], 'z': x['b']} + query = Query().map(rekey).z == 10 + assert query({'a': 5, 'b': 10}) + + +def test_eq(): + query = Query().value == 1 + assert query({'value': 1}) + assert not query({'value': 2}) + assert hash(query) + + query = Query().value == [0, 1] + assert query({'value': [0, 1]}) + assert not query({'value': [0, 1, 2]}) + assert hash(query) + + +def test_ne(): + query = Query().value != 1 + assert query({'value': 0}) + assert query({'value': 2}) + assert not query({'value': 1}) + assert hash(query) + + query = Query().value != [0, 1] + assert query({'value': [0, 1, 2]}) + assert not query({'value': [0, 1]}) + assert hash(query) + + +def test_lt(): + query = Query().value < 1 + assert query({'value': 0}) + assert not query({'value': 1}) + assert not query({'value': 2}) + assert hash(query) + + +def test_le(): + query = Query().value <= 1 + assert query({'value': 0}) + assert query({'value': 1}) + assert not query({'value': 2}) + assert hash(query) + + +def test_gt(): + query = Query().value > 1 + assert query({'value': 2}) + assert not query({'value': 1}) + assert hash(query) + + +def test_ge(): + query = Query().value >= 1 + assert query({'value': 2}) + assert query({'value': 1}) + assert not query({'value': 0}) + assert hash(query) + + +def test_or(): + query = ( + (Query().val1 == 1) | + (Query().val2 == 2) + ) + assert query({'val1': 1}) + assert query({'val2': 2}) + assert query({'val1': 1, 'val2': 2}) + assert not query({'val1': '', 'val2': ''}) + assert hash(query) + + +def test_and(): + query = ( + (Query().val1 == 1) & + (Query().val2 == 2) + ) + assert query({'val1': 1, 'val2': 2}) + assert not query({'val1': 1}) + assert not query({'val2': 2}) + assert not query({'val1': '', 'val2': ''}) + assert hash(query) + + +def test_not(): + query = ~ (Query().val1 == 1) + assert query({'val1': 5, 'val2': 2}) + assert not query({'val1': 1, 'val2': 2}) + assert hash(query) + + query = ( + (~ (Query().val1 == 1)) & + (Query().val2 == 2) + ) + assert query({'val1': '', 'val2': 2}) + assert query({'val2': 2}) + assert not query({'val1': 1, 'val2': 2}) + assert not query({'val1': 1}) + assert not query({'val1': '', 'val2': ''}) + assert hash(query) + + +def test_has_key(): + query = Query().val3.exists() + + assert query({'val3': 1}) + assert not query({'val1': 1, 'val2': 2}) + assert hash(query) + + +def test_regex(): + query = Query().val.matches(r'\d{2}\.') + + assert query({'val': '42.'}) + assert not query({'val': '44'}) + assert not query({'val': 'ab.'}) + assert not query({'val': 155}) + assert not query({'val': False}) + assert not query({'': None}) + assert hash(query) + + query = Query().val.search(r'\d+') + + assert query({'val': 'ab3'}) + assert not query({'val': 'abc'}) + assert not query({'val': ''}) + assert not query({'val': True}) + assert not query({'': None}) + assert hash(query) + + query = Query().val.search(r'JOHN', flags=re.IGNORECASE) + assert query({'val': 'john'}) + assert query({'val': 'xJohNx'}) + assert not query({'val': 'JOH'}) + assert not query({'val': 12}) + assert not query({'': None}) + assert hash(query) + + +def test_custom(): + def test(value): + return value == 42 + + query = Query().val.test(test) + + assert query({'val': 42}) + assert not query({'val': 40}) + assert not query({'val': '44'}) + assert not query({'': None}) + assert hash(query) + + def in_list(value, l): + return value in l + + query = Query().val.test(in_list, tuple([25, 35])) + assert not query({'val': 20}) + assert query({'val': 25}) + assert not query({'val': 30}) + assert query({'val': 35}) + assert not query({'val': 36}) + assert hash(query) + + +def test_custom_with_params(): + def test(value, minimum, maximum): + return minimum <= value <= maximum + + query = Query().val.test(test, 1, 10) + + assert query({'val': 5}) + assert not query({'val': 0}) + assert not query({'val': 11}) + assert not query({'': None}) + assert hash(query) + + +def test_any(): + query = Query().followers.any(Query().name == 'don') + + assert query({'followers': [{'name': 'don'}, {'name': 'john'}]}) + assert not query({'followers': 1}) + assert not query({}) + assert hash(query) + + query = Query().followers.any(Query().num.matches('\\d+')) + assert query({'followers': [{'num': '12'}, {'num': 'abc'}]}) + assert not query({'followers': [{'num': 'abc'}]}) + assert hash(query) + + query = Query().followers.any(['don', 'jon']) + assert query({'followers': ['don', 'greg', 'bill']}) + assert not query({'followers': ['greg', 'bill']}) + assert not query({}) + assert hash(query) + + query = Query().followers.any([{'name': 'don'}, {'name': 'john'}]) + assert query({'followers': [{'name': 'don'}, {'name': 'greg'}]}) + assert not query({'followers': [{'name': 'greg'}]}) + assert hash(query) + + +def test_all(): + query = Query().followers.all(Query().name == 'don') + assert query({'followers': [{'name': 'don'}]}) + assert not query({'followers': [{'name': 'don'}, {'name': 'john'}]}) + assert hash(query) + + query = Query().followers.all(Query().num.matches('\\d+')) + assert query({'followers': [{'num': '123'}, {'num': '456'}]}) + assert not query({'followers': [{'num': '123'}, {'num': 'abc'}]}) + assert hash(query) + + query = Query().followers.all(['don', 'john']) + assert query({'followers': ['don', 'john', 'greg']}) + assert not query({'followers': ['don', 'greg']}) + assert not query({}) + assert hash(query) + + query = Query().followers.all([{'name': 'jane'}, {'name': 'john'}]) + assert query({'followers': [{'name': 'john'}, {'name': 'jane'}]}) + assert query({'followers': [{'name': 'john'}, + {'name': 'jane'}, + {'name': 'bob'}]}) + assert not query({'followers': [{'name': 'john'}, {'name': 'bob'}]}) + assert hash(query) + + +def test_has(): + query = Query().key1.key2.exists() + str(query) # This used to cause a bug... + + assert query({'key1': {'key2': {'key3': 1}}}) + assert query({'key1': {'key2': 1}}) + assert not query({'key1': 3}) + assert not query({'key1': {'key1': 1}}) + assert not query({'key2': {'key1': 1}}) + assert hash(query) + + query = Query().key1.key2 == 1 + + assert query({'key1': {'key2': 1}}) + assert not query({'key1': {'key2': 2}}) + assert hash(query) + + # Nested has: key exists + query = Query().key1.key2.key3.exists() + assert query({'key1': {'key2': {'key3': 1}}}) + # Not a dict + assert not query({'key1': 1}) + assert not query({'key1': {'key2': 1}}) + # Wrong key + assert not query({'key1': {'key2': {'key0': 1}}}) + assert not query({'key1': {'key0': {'key3': 1}}}) + assert not query({'key0': {'key2': {'key3': 1}}}) + + assert hash(query) + + # Nested has: check for value + query = Query().key1.key2.key3 == 1 + assert query({'key1': {'key2': {'key3': 1}}}) + assert not query({'key1': {'key2': {'key3': 0}}}) + assert hash(query) + + # Test special methods: regex matches + query = Query().key1.value.matches(r'\d+') + assert query({'key1': {'value': '123'}}) + assert not query({'key2': {'value': '123'}}) + assert not query({'key2': {'value': 'abc'}}) + assert hash(query) + + # Test special methods: regex contains + query = Query().key1.value.search(r'\d+') + assert query({'key1': {'value': 'a2c'}}) + assert not query({'key2': {'value': 'a2c'}}) + assert not query({'key2': {'value': 'abc'}}) + assert hash(query) + + # Test special methods: nested has and regex matches + query = Query().key1.x.y.matches(r'\d+') + assert query({'key1': {'x': {'y': '123'}}}) + assert not query({'key1': {'x': {'y': 'abc'}}}) + assert hash(query) + + # Test special method: nested has and regex contains + query = Query().key1.x.y.search(r'\d+') + assert query({'key1': {'x': {'y': 'a2c'}}}) + assert not query({'key1': {'x': {'y': 'abc'}}}) + assert hash(query) + + # Test special methods: custom test + query = Query().key1.int.test(lambda x: x == 3) + assert query({'key1': {'int': 3}}) + assert hash(query) + + +def test_one_of(): + query = Query().key1.one_of(['value 1', 'value 2']) + assert query({'key1': 'value 1'}) + assert query({'key1': 'value 2'}) + assert not query({'key1': 'value 3'}) + + +def test_hash(): + d = { + Query().key1 == 2: True, + Query().key1.key2.key3.exists(): True, + Query().key1.exists() & Query().key2.exists(): True, + Query().key1.exists() | Query().key2.exists(): True, + } + + assert (Query().key1 == 2) in d + assert (Query().key1.key2.key3.exists()) in d + assert (Query()['key1.key2'].key3.exists()) not in d + + # Commutative property of & and | + assert (Query().key1.exists() & Query().key2.exists()) in d + assert (Query().key2.exists() & Query().key1.exists()) in d + assert (Query().key1.exists() | Query().key2.exists()) in d + assert (Query().key2.exists() | Query().key1.exists()) in d + + +def test_orm_usage(): + data = {'name': 'John', 'age': {'year': 2000}} + + User = Query() + query1 = User.name == 'John' + query2 = User.age.year == 2000 + assert query1(data) + assert query2(data) + + +def test_repr(): + Fruit = Query() + + assert repr(Fruit) == "Query()" + assert repr(Fruit.type == 'peach') == "QueryImpl('==', ('type',), 'peach')" + + +def test_subclass(): + # Test that a new query test method in a custom subclass is properly usable + class MyQueryClass(Query): + def equal_double(self, rhs): + return self._generate_test( + lambda value: value == rhs * 2, + ('equal_double', self._path, rhs) + ) + + query = MyQueryClass().val.equal_double('42') + + assert query({'val': '4242'}) + assert not query({'val': '42'}) + assert not query({'': None}) + assert hash(query) + + +def test_noop(): + query = Query().noop() + + assert query({'foo': True}) + assert query({'foo': None}) + assert query({}) + + +def test_equality(): + q = Query() + assert (q.foo == 2) != 0 + assert (q.foo == 'yes') != '' + + +def test_empty_query_error(): + with pytest.raises(RuntimeError, match='Empty query was evaluated'): + Query()({}) + + +def test_fragment(): + query = Query().fragment({'a': 4, 'b': True}) + + assert query({'a': 4, 'b': True, 'c': 'yes'}) + assert not query({'a': 4, 'c': 'yes'}) + assert not query({'b': True, 'c': 'yes'}) + assert not query({'a': 5, 'b': True, 'c': 'yes'}) + assert not query({'a': 4, 'b': 'no', 'c': 'yes'}) + + +def test_fragment_with_path(): + query = Query().doc.fragment({'a': 4, 'b': True}) + + assert query({'doc': {'a': 4, 'b': True, 'c': 'yes'}}) + assert not query({'a': 4, 'b': True, 'c': 'yes'}) + assert not query({'doc': {'a': 4, 'c': 'yes'}}) + + +def test_get_item(): + query = Query()['test'] == 1 + + assert query({'test': 1}) + assert not query({'test': 0}) diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_storages.py b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_storages.py new file mode 100644 index 0000000000000000000000000000000000000000..3cab11c3fe94d706234c5b125c2e7c430bbbf303 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_storages.py @@ -0,0 +1,281 @@ +import json +import os +import random +import tempfile + +import pytest + +from tinydb import TinyDB, where +from tinydb.storages import JSONStorage, MemoryStorage, Storage, touch +from tinydb.table import Document + +random.seed() + +doc = {'none': [None, None], 'int': 42, 'float': 3.1415899999999999, + 'list': ['LITE', 'RES_ACID', 'SUS_DEXT'], + 'dict': {'hp': 13, 'sp': 5}, + 'bool': [True, False, True, False]} + + +def test_json(tmpdir): + # Write contents + path = str(tmpdir.join('test.db')) + storage = JSONStorage(path) + storage.write(doc) + + # Verify contents + assert doc == storage.read() + storage.close() + + +def test_json_kwargs(tmpdir): + db_file = tmpdir.join('test.db') + db = TinyDB(str(db_file), sort_keys=True, indent=4, separators=(',', ': ')) + + # Write contents + db.insert({'b': 1}) + db.insert({'a': 1}) + + assert db_file.read() == '''{ + "_default": { + "1": { + "b": 1 + }, + "2": { + "a": 1 + } + } +}''' + db.close() + + +def test_json_readwrite(tmpdir): + """ + Regression test for issue #1 + """ + path = str(tmpdir.join('test.db')) + + # Create TinyDB instance + db = TinyDB(path, storage=JSONStorage) + + item = {'name': 'A very long entry'} + item2 = {'name': 'A short one'} + + def get(s): + return db.get(where('name') == s) + + db.insert(item) + assert get('A very long entry') == item + + db.remove(where('name') == 'A very long entry') + assert get('A very long entry') is None + + db.insert(item2) + assert get('A short one') == item2 + + db.remove(where('name') == 'A short one') + assert get('A short one') is None + + db.close() + + +def test_json_read(tmpdir): + r"""Open a database only for reading""" + path = str(tmpdir.join('test.db')) + with pytest.raises(FileNotFoundError): + db = TinyDB(path, storage=JSONStorage, access_mode='r') + # Create small database + db = TinyDB(path, storage=JSONStorage) + db.insert({'b': 1}) + db.insert({'a': 1}) + db.close() + # Access in read mode + db = TinyDB(path, storage=JSONStorage, access_mode='r') + assert db.get(where('a') == 1) == {'a': 1} # reading is fine + with pytest.raises(IOError): + db.insert({'c': 1}) # writing is not + db.close() + + +def test_create_dirs(): + temp_dir = tempfile.gettempdir() + + while True: + dname = os.path.join(temp_dir, str(random.getrandbits(20))) + if not os.path.exists(dname): + db_dir = dname + db_file = os.path.join(db_dir, 'db.json') + break + + with pytest.raises(IOError): + JSONStorage(db_file) + + JSONStorage(db_file, create_dirs=True).close() + assert os.path.exists(db_file) + + # Use create_dirs with already existing directory + JSONStorage(db_file, create_dirs=True).close() + assert os.path.exists(db_file) + + os.remove(db_file) + os.rmdir(db_dir) + + +def test_json_invalid_directory(): + with pytest.raises(IOError): + with TinyDB('/this/is/an/invalid/path/db.json', storage=JSONStorage): + pass + + +def test_in_memory(): + # Write contents + storage = MemoryStorage() + storage.write(doc) + + # Verify contents + assert doc == storage.read() + + # Test case for #21 + other = MemoryStorage() + other.write({}) + assert other.read() != storage.read() + + +def test_in_memory_close(): + with TinyDB(storage=MemoryStorage) as db: + db.insert({}) + + +def test_custom(): + # noinspection PyAbstractClass + class MyStorage(Storage): + pass + + with pytest.raises(TypeError): + MyStorage() + + +def test_read_once(): + count = 0 + + # noinspection PyAbstractClass + class MyStorage(Storage): + def __init__(self): + self.memory = None + + def read(self): + nonlocal count + count += 1 + + return self.memory + + def write(self, data): + self.memory = data + + with TinyDB(storage=MyStorage) as db: + assert count == 0 + + db.table(db.default_table_name) + + assert count == 0 + + db.all() + + assert count == 1 + + db.insert({'foo': 'bar'}) + + assert count == 3 # One for getting the next ID, one for the insert + + db.all() + + assert count == 4 + + +def test_custom_with_exception(): + class MyStorage(Storage): + def read(self): + pass + + def write(self, data): + pass + + def __init__(self): + raise ValueError() + + def close(self): + raise RuntimeError() + + with pytest.raises(ValueError): + with TinyDB(storage=MyStorage) as db: + pass + + +def test_yaml(tmpdir): + """ + :type tmpdir: py._path.local.LocalPath + """ + + try: + import yaml + except ImportError: + return pytest.skip('PyYAML not installed') + + def represent_doc(dumper, data): + # Represent `Document` objects as their dict's string representation + # which PyYAML understands + return dumper.represent_data(dict(data)) + + yaml.add_representer(Document, represent_doc) + + class YAMLStorage(Storage): + def __init__(self, filename): + self.filename = filename + touch(filename, False) + + def read(self): + with open(self.filename) as handle: + data = yaml.safe_load(handle.read()) + return data + + def write(self, data): + with open(self.filename, 'w') as handle: + yaml.dump(data, handle) + + def close(self): + pass + + # Write contents + path = str(tmpdir.join('test.db')) + db = TinyDB(path, storage=YAMLStorage) + db.insert(doc) + assert db.all() == [doc] + + db.update({'name': 'foo'}) + + assert '!' not in tmpdir.join('test.db').read() + + assert db.contains(where('name') == 'foo') + assert len(db) == 1 + + +def test_encoding(tmpdir): + japanese_doc = {"Test": u"こんにちは世界"} + + path = str(tmpdir.join('test.db')) + # cp936 is used for japanese encodings + jap_storage = JSONStorage(path, encoding="cp936") + jap_storage.write(japanese_doc) + + try: + exception = json.decoder.JSONDecodeError + except AttributeError: + exception = ValueError + + with pytest.raises(exception): + # cp037 is used for english encodings + eng_storage = JSONStorage(path, encoding="cp037") + eng_storage.read() + + jap_storage = JSONStorage(path, encoding="cp936") + assert japanese_doc == jap_storage.read() diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_tables.py b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..4335200abaa2edd0b063bc6ac9943c0297589347 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_tables.py @@ -0,0 +1,179 @@ +import re + +import pytest + +from tinydb import where + + +def test_next_id(db): + db.truncate() + + assert db._get_next_id() == 1 + assert db._get_next_id() == 2 + assert db._get_next_id() == 3 + + +def test_tables_list(db): + db.table('table1').insert({'a': 1}) + db.table('table2').insert({'a': 1}) + + assert db.tables() == {'_default', 'table1', 'table2'} + + +def test_one_table(db): + table1 = db.table('table1') + + table1.insert_multiple({'int': 1, 'char': c} for c in 'abc') + + assert table1.get(where('int') == 1)['char'] == 'a' + assert table1.get(where('char') == 'b')['char'] == 'b' + + +def test_multiple_tables(db): + table1 = db.table('table1') + table2 = db.table('table2') + table3 = db.table('table3') + + table1.insert({'int': 1, 'char': 'a'}) + table2.insert({'int': 1, 'char': 'b'}) + table3.insert({'int': 1, 'char': 'c'}) + + assert table1.count(where('char') == 'a') == 1 + assert table2.count(where('char') == 'b') == 1 + assert table3.count(where('char') == 'c') == 1 + + db.drop_tables() + + assert len(table1) == 0 + assert len(table2) == 0 + assert len(table3) == 0 + + +def test_caching(db): + table1 = db.table('table1') + table2 = db.table('table1') + + assert table1 is table2 + + +def test_query_cache(db): + query1 = where('int') == 1 + + assert db.count(query1) == 3 + assert query1 in db._query_cache + + assert db.count(query1) == 3 + assert query1 in db._query_cache + + query2 = where('int') == 0 + + assert db.count(query2) == 0 + assert query2 in db._query_cache + + assert db.count(query2) == 0 + assert query2 in db._query_cache + + +def test_query_cache_with_mutable_callable(db): + table = db.table('table') + table.insert({'val': 5}) + + mutable = 5 + increase = lambda x: x + mutable + + assert where('val').is_cacheable() + assert not where('val').map(increase).is_cacheable() + assert not (where('val').map(increase) == 10).is_cacheable() + + search = where('val').map(increase) == 10 + assert table.count(search) == 1 + + # now `increase` would yield 15, not 10 + mutable = 10 + + assert table.count(search) == 0 + assert len(table._query_cache) == 0 + + +def test_zero_cache_size(db): + table = db.table('table3', cache_size=0) + query = where('int') == 1 + + table.insert({'int': 1}) + table.insert({'int': 1}) + + assert table.count(query) == 2 + assert table.count(where('int') == 2) == 0 + assert len(table._query_cache) == 0 + + +def test_query_cache_size(db): + table = db.table('table3', cache_size=1) + query = where('int') == 1 + + table.insert({'int': 1}) + table.insert({'int': 1}) + + assert table.count(query) == 2 + assert table.count(where('int') == 2) == 0 + assert len(table._query_cache) == 1 + + +def test_lru_cache(db): + # Test integration into TinyDB + table = db.table('table3', cache_size=2) + query = where('int') == 1 + + table.search(query) + table.search(where('int') == 2) + table.search(where('int') == 3) + assert query not in table._query_cache + + table.remove(where('int') == 1) + assert not table._query_cache.lru + + table.search(query) + + assert len(table._query_cache) == 1 + table.clear_cache() + assert len(table._query_cache) == 0 + + +def test_table_is_iterable(db): + table = db.table('table1') + + table.insert_multiple({'int': i} for i in range(3)) + + assert [r for r in table] == table.all() + + +def test_table_name(db): + name = 'table3' + table = db.table(name) + assert name == table.name + + with pytest.raises(AttributeError): + table.name = 'foo' + + +def test_table_repr(db): + name = 'table4' + table = db.table(name) + + assert re.match( + r">", + repr(table)) + + +def test_truncate_table(db): + db.truncate() + assert db._get_next_id() == 1 + + +def test_persist_table(db): + db.table("persisted", persist_empty=True) + assert "persisted" in db.tables() + + db.table("nonpersisted", persist_empty=False) + assert "nonpersisted" not in db.tables() diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_tinydb.py b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_tinydb.py new file mode 100644 index 0000000000000000000000000000000000000000..655027a5b2640113d24c572be6689aaf4fea3011 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_tinydb.py @@ -0,0 +1,716 @@ +import re +from collections.abc import Mapping + +import pytest + +from tinydb import TinyDB, where, Query +from tinydb.middlewares import Middleware, CachingMiddleware +from tinydb.storages import MemoryStorage, JSONStorage +from tinydb.table import Document + + +def test_drop_tables(db: TinyDB): + db.drop_tables() + + db.insert({}) + db.drop_tables() + + assert len(db) == 0 + + +def test_all(db: TinyDB): + db.drop_tables() + + for i in range(10): + db.insert({}) + + assert len(db.all()) == 10 + + +def test_insert(db: TinyDB): + db.drop_tables() + db.insert({'int': 1, 'char': 'a'}) + + assert db.count(where('int') == 1) == 1 + + db.drop_tables() + + db.insert({'int': 1, 'char': 'a'}) + db.insert({'int': 1, 'char': 'b'}) + db.insert({'int': 1, 'char': 'c'}) + + assert db.count(where('int') == 1) == 3 + assert db.count(where('char') == 'a') == 1 + + +def test_insert_ids(db: TinyDB): + db.drop_tables() + assert db.insert({'int': 1, 'char': 'a'}) == 1 + assert db.insert({'int': 1, 'char': 'a'}) == 2 + + +def test_insert_with_doc_id(db: TinyDB): + db.drop_tables() + assert db.insert({'int': 1, 'char': 'a'}) == 1 + assert db.insert(Document({'int': 1, 'char': 'a'}, 12)) == 12 + assert db.insert(Document({'int': 1, 'char': 'a'}, 77)) == 77 + assert db.insert({'int': 1, 'char': 'a'}) == 78 + + +def test_insert_with_duplicate_doc_id(db: TinyDB): + db.drop_tables() + assert db.insert({'int': 1, 'char': 'a'}) == 1 + + with pytest.raises(ValueError): + db.insert(Document({'int': 1, 'char': 'a'}, 1)) + + +def test_insert_multiple(db: TinyDB): + db.drop_tables() + assert not db.contains(where('int') == 1) + + # Insert multiple from list + db.insert_multiple([{'int': 1, 'char': 'a'}, + {'int': 1, 'char': 'b'}, + {'int': 1, 'char': 'c'}]) + + assert db.count(where('int') == 1) == 3 + assert db.count(where('char') == 'a') == 1 + + # Insert multiple from generator function + def generator(): + for j in range(10): + yield {'int': j} + + db.drop_tables() + + db.insert_multiple(generator()) + + for i in range(10): + assert db.count(where('int') == i) == 1 + assert db.count(where('int').exists()) == 10 + + # Insert multiple from inline generator + db.drop_tables() + + db.insert_multiple({'int': i} for i in range(10)) + + for i in range(10): + assert db.count(where('int') == i) == 1 + + +def test_insert_multiple_with_ids(db: TinyDB): + db.drop_tables() + + # Insert multiple from list + assert db.insert_multiple([{'int': 1, 'char': 'a'}, + {'int': 1, 'char': 'b'}, + {'int': 1, 'char': 'c'}]) == [1, 2, 3] + + +def test_insert_multiple_with_doc_ids(db: TinyDB): + db.drop_tables() + + assert db.insert_multiple([ + Document({'int': 1, 'char': 'a'}, 12), + Document({'int': 1, 'char': 'b'}, 77) + ]) == [12, 77] + assert db.get(doc_id=12) == {'int': 1, 'char': 'a'} + assert db.get(doc_id=77) == {'int': 1, 'char': 'b'} + + with pytest.raises(ValueError): + db.insert_multiple([Document({'int': 1, 'char': 'a'}, 12)]) + + +def test_insert_invalid_type_raises_error(db: TinyDB): + with pytest.raises(ValueError, match='Document is not a Mapping'): + # object() as an example of a non-mapping-type + db.insert(object()) # type: ignore + + +def test_insert_valid_mapping_type(db: TinyDB): + class CustomDocument(Mapping): + def __init__(self, data): + self.data = data + + def __getitem__(self, key): + return self.data[key] + + def __iter__(self): + return iter(self.data) + + def __len__(self): + return len(self.data) + + db.drop_tables() + db.insert(CustomDocument({'int': 1, 'char': 'a'})) + assert db.count(where('int') == 1) == 1 + + +def test_custom_mapping_type_with_json(tmpdir): + class CustomDocument(Mapping): + def __init__(self, data): + self.data = data + + def __getitem__(self, key): + return self.data[key] + + def __iter__(self): + return iter(self.data) + + def __len__(self): + return len(self.data) + + # Insert + db = TinyDB(str(tmpdir.join('test.db'))) + db.drop_tables() + db.insert(CustomDocument({'int': 1, 'char': 'a'})) + assert db.count(where('int') == 1) == 1 + + # Insert multiple + db.insert_multiple([ + CustomDocument({'int': 2, 'char': 'a'}), + CustomDocument({'int': 3, 'char': 'a'}) + ]) + assert db.count(where('int') == 1) == 1 + assert db.count(where('int') == 2) == 1 + assert db.count(where('int') == 3) == 1 + + # Write back + doc_id = db.get(where('int') == 3).doc_id + db.update(CustomDocument({'int': 4, 'char': 'a'}), doc_ids=[doc_id]) + assert db.count(where('int') == 3) == 0 + assert db.count(where('int') == 4) == 1 + + +def test_remove(db: TinyDB): + db.remove(where('char') == 'b') + + assert len(db) == 2 + assert db.count(where('int') == 1) == 2 + + +def test_remove_all_fails(db: TinyDB): + with pytest.raises(RuntimeError): + db.remove() + + +def test_remove_multiple(db: TinyDB): + db.remove(where('int') == 1) + + assert len(db) == 0 + + +def test_remove_ids(db: TinyDB): + db.remove(doc_ids=[1, 2]) + + assert len(db) == 1 + + +def test_remove_returns_ids(db: TinyDB): + assert db.remove(where('char') == 'b') == [2] + + +def test_update(db: TinyDB): + assert len(db) == 3 + + db.update({'int': 2}, where('char') == 'a') + + assert db.count(where('int') == 2) == 1 + assert db.count(where('int') == 1) == 2 + + +def test_update_all(db: TinyDB): + assert db.count(where('int') == 1) == 3 + + db.update({'newField': True}) + + assert db.count(where('newField') == True) == 3 # noqa + + +def test_update_returns_ids(db: TinyDB): + db.drop_tables() + assert db.insert({'int': 1, 'char': 'a'}) == 1 + assert db.insert({'int': 1, 'char': 'a'}) == 2 + + assert db.update({'char': 'b'}, where('int') == 1) == [1, 2] + + +def test_update_transform(db: TinyDB): + def increment(field): + def transform(el): + el[field] += 1 + + return transform + + def delete(field): + def transform(el): + del el[field] + + return transform + + assert db.count(where('int') == 1) == 3 + + db.update(increment('int'), where('char') == 'a') + db.update(delete('char'), where('char') == 'a') + + assert db.count(where('int') == 2) == 1 + assert db.count(where('char') == 'a') == 0 + assert db.count(where('int') == 1) == 2 + + +def test_update_ids(db: TinyDB): + db.update({'int': 2}, doc_ids=[1, 2]) + + assert db.count(where('int') == 2) == 2 + + +def test_update_multiple(db: TinyDB): + assert len(db) == 3 + + db.update_multiple([ + ({'int': 2}, where('char') == 'a'), + ({'int': 4}, where('char') == 'b'), + ]) + + assert db.count(where('int') == 1) == 1 + assert db.count(where('int') == 2) == 1 + assert db.count(where('int') == 4) == 1 + + +def test_update_multiple_operation(db: TinyDB): + def increment(field): + def transform(el): + el[field] += 1 + + return transform + + assert db.count(where('int') == 1) == 3 + + db.update_multiple([ + (increment('int'), where('char') == 'a'), + (increment('int'), where('char') == 'b') + ]) + + assert db.count(where('int') == 2) == 2 + + +def test_upsert(db: TinyDB): + assert len(db) == 3 + + # Document existing + db.upsert({'int': 5}, where('char') == 'a') + assert db.count(where('int') == 5) == 1 + + # Document missing + assert db.upsert({'int': 9, 'char': 'x'}, where('char') == 'x') == [4] + assert db.count(where('int') == 9) == 1 + + +def test_upsert_by_id(db: TinyDB): + assert len(db) == 3 + + # Single document existing + extant_doc = Document({'char': 'v'}, doc_id=1) + assert db.upsert(extant_doc) == [1] + doc = db.get(where('char') == 'v') + assert isinstance(doc, Document) + assert doc is not None + assert doc.doc_id == 1 + assert len(db) == 3 + + # Single document missing + missing_doc = Document({'int': 5, 'char': 'w'}, doc_id=5) + assert db.upsert(missing_doc) == [5] + doc = db.get(where('char') == 'w') + assert isinstance(doc, Document) + assert doc is not None + assert doc.doc_id == 5 + assert len(db) == 4 + + # Missing doc_id and condition + with pytest.raises(ValueError, match=r"(?=.*\bdoc_id\b)(?=.*\bquery\b)"): + db.upsert({'no_Document': 'no_query'}) + + # Make sure we didn't break anything + assert db.insert({'check': '_next_id'}) == 6 + + +def test_search(db: TinyDB): + assert not db._query_cache + assert len(db.search(where('int') == 1)) == 3 + + assert len(db._query_cache) == 1 + assert len(db.search(where('int') == 1)) == 3 # Query result from cache + + +def test_search_path(db: TinyDB): + assert not db._query_cache + assert len(db.search(where('int').exists())) == 3 + assert len(db._query_cache) == 1 + + assert len(db.search(where('asd').exists())) == 0 + assert len(db.search(where('int').exists())) == 3 # Query result from cache + + +def test_search_no_results_cache(db: TinyDB): + assert len(db.search(where('missing').exists())) == 0 + assert len(db.search(where('missing').exists())) == 0 + + +def test_get(db: TinyDB): + item = db.get(where('char') == 'b') + assert isinstance(item, Document) + assert item is not None + assert item['char'] == 'b' + + +def test_get_ids(db: TinyDB): + el = db.all()[0] + assert db.get(doc_id=el.doc_id) == el + assert db.get(doc_id=float('NaN')) is None # type: ignore + + +def test_get_multiple_ids(db: TinyDB): + el = db.all() + assert db.get(doc_ids=[x.doc_id for x in el]) == el + + +def test_get_invalid(db: TinyDB): + with pytest.raises(RuntimeError): + db.get() + + +def test_count(db: TinyDB): + assert db.count(where('int') == 1) == 3 + assert db.count(where('char') == 'd') == 0 + + +def test_contains(db: TinyDB): + assert db.contains(where('int') == 1) + assert not db.contains(where('int') == 0) + + +def test_contains_ids(db: TinyDB): + assert db.contains(doc_id=1) + assert db.contains(doc_id=2) + assert not db.contains(doc_id=88) + + +def test_contains_invalid(db: TinyDB): + with pytest.raises(RuntimeError): + db.contains() + + +def test_get_idempotent(db: TinyDB): + u = db.get(where('int') == 1) + z = db.get(where('int') == 1) + assert u == z + + +def test_multiple_dbs(): + """ + Regression test for issue #3 + """ + db1 = TinyDB(storage=MemoryStorage) + db2 = TinyDB(storage=MemoryStorage) + + db1.insert({'int': 1, 'char': 'a'}) + db1.insert({'int': 1, 'char': 'b'}) + db1.insert({'int': 1, 'value': 5.0}) + + db2.insert({'color': 'blue', 'animal': 'turtle'}) + + assert len(db1) == 3 + assert len(db2) == 1 + + +def test_storage_closed_once(): + class Storage: + def __init__(self): + self.closed = False + + def read(self): + return {} + + def write(self, data): + pass + + def close(self): + assert not self.closed + self.closed = True + + with TinyDB(storage=Storage) as db: + db.close() + + del db + # If db.close() is called during cleanup, the assertion will fail and throw + # and exception + + +def test_unique_ids(tmpdir): + """ + :type tmpdir: py._path.local.LocalPath + """ + path = str(tmpdir.join('db.json')) + + # Verify ids are unique when reopening the DB and inserting + with TinyDB(path) as _db: + _db.insert({'x': 1}) + + with TinyDB(path) as _db: + _db.insert({'x': 1}) + + with TinyDB(path) as _db: + data = _db.all() + + assert data[0].doc_id != data[1].doc_id + + # Verify ids stay unique when inserting/removing + with TinyDB(path) as _db: + _db.drop_tables() + _db.insert_multiple({'x': i} for i in range(5)) + _db.remove(where('x') == 2) + + assert len(_db) == 4 + + ids = [e.doc_id for e in _db.all()] + assert len(ids) == len(set(ids)) + + +def test_lastid_after_open(tmpdir): + """ + Regression test for issue #34 + + :type tmpdir: py._path.local.LocalPath + """ + + NUM = 100 + path = str(tmpdir.join('db.json')) + + with TinyDB(path) as _db: + _db.insert_multiple({'i': i} for i in range(NUM)) + + with TinyDB(path) as _db: + assert _db._get_next_id() - 1 == NUM + + +def test_doc_ids_json(tmpdir): + """ + Regression test for issue #45 + """ + + path = str(tmpdir.join('db.json')) + + with TinyDB(path) as _db: + _db.drop_tables() + assert _db.insert({'int': 1, 'char': 'a'}) == 1 + assert _db.insert({'int': 1, 'char': 'a'}) == 2 + + _db.drop_tables() + assert _db.insert_multiple([{'int': 1, 'char': 'a'}, + {'int': 1, 'char': 'b'}, + {'int': 1, 'char': 'c'}]) == [1, 2, 3] + + assert _db.contains(doc_id=1) + assert _db.contains(doc_id=2) + assert not _db.contains(doc_id=88) + + _db.update({'int': 2}, doc_ids=[1, 2]) + assert _db.count(where('int') == 2) == 2 + + el = _db.all()[0] + assert _db.get(doc_id=el.doc_id) == el + assert _db.get(doc_id=float('NaN')) is None + + _db.remove(doc_ids=[1, 2]) + assert len(_db) == 1 + + +def test_insert_string(tmpdir): + path = str(tmpdir.join('db.json')) + + with TinyDB(path) as _db: + data = [{'int': 1}, {'int': 2}] + _db.insert_multiple(data) + + with pytest.raises(ValueError): + _db.insert([1, 2, 3]) # Fails + + with pytest.raises(ValueError): + _db.insert({'bark'}) # Fails + + assert data == _db.all() + + _db.insert({'int': 3}) # Does not fail + + +def test_insert_invalid_dict(tmpdir): + path = str(tmpdir.join('db.json')) + + with TinyDB(path) as _db: + data = [{'int': 1}, {'int': 2}] + _db.insert_multiple(data) + + with pytest.raises(TypeError): + _db.insert({'int': _db}) # Fails + + assert data == _db.all() + + _db.insert({'int': 3}) # Does not fail + + +def test_gc(tmpdir): + # See https://github.com/msiemens/tinydb/issues/92 + path = str(tmpdir.join('db.json')) + db = TinyDB(path) + table = db.table('foo') + table.insert({'something': 'else'}) + table.insert({'int': 13}) + assert len(table.search(where('int') == 13)) == 1 + assert table.all() == [{'something': 'else'}, {'int': 13}] + db.close() + + +def test_drop_table(): + db = TinyDB(storage=MemoryStorage) + default_table_name = db.table(db.default_table_name).name + + assert [] == list(db.tables()) + db.drop_table(default_table_name) + + db.insert({'a': 1}) + assert [default_table_name] == list(db.tables()) + + db.drop_table(default_table_name) + assert [] == list(db.tables()) + + table_name = 'some-other-table' + db = TinyDB(storage=MemoryStorage) + db.table(table_name).insert({'a': 1}) + assert {table_name} == db.tables() + + db.drop_table(table_name) + assert set() == db.tables() + assert table_name not in db._tables + + db.drop_table('non-existent-table-name') + assert set() == db.tables() + + +def test_empty_write(tmpdir): + path = str(tmpdir.join('db.json')) + + class ReadOnlyMiddleware(Middleware): + def write(self, data): + raise AssertionError('No write for unchanged db') + + TinyDB(path).close() + TinyDB(path, storage=ReadOnlyMiddleware(JSONStorage)).close() + + +def test_query_cache(): + db = TinyDB(storage=MemoryStorage) + db.insert_multiple([ + {'name': 'foo', 'value': 42}, + {'name': 'bar', 'value': -1337} + ]) + + query = where('value') > 0 + + results = db.search(query) + assert len(results) == 1 + + # Modify the db instance to not return any results when + # bypassing the query cache + db._tables[db.table(db.default_table_name).name]._read_table = lambda: {} + + # Make sure we got an independent copy of the result list + results.extend([1]) + assert db.search(query) == [{'name': 'foo', 'value': 42}] + + +def test_tinydb_is_iterable(db: TinyDB): + assert [r for r in db] == db.all() + + +def test_repr(tmpdir): + path = str(tmpdir.join('db.json')) + + db = TinyDB(path) + db.insert({'a': 1}) + + assert re.match( + r"", + repr(db)) + + +def test_delete(tmpdir): + path = str(tmpdir.join('db.json')) + + db = TinyDB(path, ensure_ascii=False) + q = Query() + db.insert({'network': {'id': '114', 'name': 'ok', 'rpc': 'dac', + 'ticker': 'mkay'}}) + assert db.search(q.network.id == '114') == [ + {'network': {'id': '114', 'name': 'ok', 'rpc': 'dac', + 'ticker': 'mkay'}} + ] + db.remove(q.network.id == '114') + assert db.search(q.network.id == '114') == [] + + +def test_insert_multiple_with_single_dict(db: TinyDB): + with pytest.raises(ValueError): + d = {'first': 'John', 'last': 'smith'} + db.insert_multiple(d) # type: ignore + db.close() + + +def test_access_storage(): + assert isinstance(TinyDB(storage=MemoryStorage).storage, + MemoryStorage) + assert isinstance(TinyDB(storage=CachingMiddleware(MemoryStorage)).storage, + CachingMiddleware) + + +def test_empty_db_len(): + db = TinyDB(storage=MemoryStorage) + assert len(db) == 0 + + +def test_insert_on_existing_db(tmpdir): + path = str(tmpdir.join('db.json')) + + db = TinyDB(path, ensure_ascii=False) + db.insert({'foo': 'bar'}) + + assert len(db) == 1 + + db.close() + + db = TinyDB(path, ensure_ascii=False) + db.insert({'foo': 'bar'}) + db.insert({'foo': 'bar'}) + + assert len(db) == 3 + + +def test_storage_access(): + db = TinyDB(storage=MemoryStorage) + + assert isinstance(db.storage, MemoryStorage) + + +def test_lambda_query(): + db = TinyDB(storage=MemoryStorage) + db.insert({'foo': 'bar'}) + + query = lambda doc: doc.get('foo') == 'bar' + query.is_cacheable = lambda: False + assert db.search(query) == [{'foo': 'bar'}] + assert not db._query_cache diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_utils.py b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..031e086f6b91dc8e4959f6a3d62bdb9c1cf0687a --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/tests/trusted/tests/test_utils.py @@ -0,0 +1,116 @@ +import pytest + +from tinydb.utils import LRUCache, freeze, FrozenDict + + +def test_lru_cache(): + cache = LRUCache(capacity=3) + cache["a"] = 1 + cache["b"] = 2 + cache["c"] = 3 + _ = cache["a"] # move to front in lru queue + cache["d"] = 4 # move oldest item out of lru queue + + try: + _ = cache['f'] + except KeyError: + pass + + assert cache.lru == ["c", "a", "d"] + + +def test_lru_cache_set_multiple(): + cache = LRUCache(capacity=3) + cache["a"] = 1 + cache["a"] = 2 + cache["a"] = 3 + cache["a"] = 4 + + assert cache.lru == ["a"] + + +def test_lru_cache_set_update(): + cache = LRUCache(capacity=3) + cache["a"] = 1 + cache["a"] = 2 + + assert cache["a"] == 2 + + +def test_lru_cache_get(): + cache = LRUCache(capacity=3) + cache["a"] = 1 + cache["b"] = 1 + cache["c"] = 1 + cache.get("a") + cache["d"] = 4 + + assert cache.lru == ["c", "a", "d"] + + +def test_lru_cache_delete(): + cache = LRUCache(capacity=3) + cache["a"] = 1 + cache["b"] = 2 + del cache["a"] + + try: + del cache['f'] + except KeyError: + pass + + assert cache.lru == ["b"] + + +def test_lru_cache_clear(): + cache = LRUCache(capacity=3) + cache["a"] = 1 + cache["b"] = 2 + cache.clear() + + assert cache.lru == [] + + +def test_lru_cache_unlimited(): + cache = LRUCache() + for i in range(100): + cache[i] = i + + assert len(cache.lru) == 100 + + +def test_lru_cache_unlimited_explicit(): + cache = LRUCache(capacity=None) + for i in range(100): + cache[i] = i + + assert len(cache.lru) == 100 + + +def test_lru_cache_iteration_works(): + cache = LRUCache() + count = 0 + for _ in cache: + assert False, 'there should be no elements in the cache' + + assert count == 0 + + +def test_freeze(): + frozen = freeze([0, 1, 2, {'a': [1, 2, 3]}, {1, 2}]) + assert isinstance(frozen, tuple) + assert isinstance(frozen[3], FrozenDict) + assert isinstance(frozen[3]['a'], tuple) + assert isinstance(frozen[4], frozenset) + + with pytest.raises(TypeError): + frozen[0] = 10 + + with pytest.raises(TypeError): + frozen[3]['a'] = 10 + + with pytest.raises(TypeError): + frozen[3].pop('a') + + with pytest.raises(TypeError): + frozen[3].update({'a': 9}) diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/validation/canaries/first-hunk-only.sh b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..8ed3726ffb76757c60248e483112bd4bef277aae --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/validation/canaries/first-hunk-only.sh @@ -0,0 +1,42 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/tinydb/database.py b/tinydb/database.py +index 3b36269d02892e833fc23e75cb089a32ec1d2533..4a73c466f639b166c3a51f7544ce4e81a1e5e5b4 100644 +--- a/tinydb/database.py ++++ b/tinydb/database.py +@@ -180,22 +180,25 @@ + :param name: The name of the table to drop. + """ + ++ # If the table is currently opened, we need to forget the table class ++ # instance + if name in self._tables: + del self._tables[name] + + data = self.storage.read() + ++ # The database is uninitialized, there's nothing to do + if data is None: + return + +- # The logic of checking table existence is altered +- if name in data: ++ # The table does not exist, there's nothing to do ++ if name not in data: + return + +- # Incorrectly skip removing table data +- del data +- +- # Incorrectly write the unmodified data back to the storage ++ # Remove the table from the data dict ++ del data[name] ++ ++ # Store the updated data back to the storage + self.storage.write(data) + + @property +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/validation/canaries/original-bug.sh b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/validation/openenv.json b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__0176isok/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/LICENSE.source b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..611d35661f933a4469c941e6c97578c22673b4ab --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/LICENSE.source @@ -0,0 +1,7 @@ +Copyright (C) 2013 Markus Siemens + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/adapter.json b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..f84654c47a73e564bd0c813c1572b8adcbc1550f --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "0551e0806afd99add5cb7c6184a7e0b4813c16aa421c4031e64e7e3a27b44236", + "gold_patch_sha256": "0b357f6329d9b7ad4a68c1e58e21acdadac483e41a4b99ccc738d0686b12ce1e", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "ac93b71b987a331f1e45ea2b7d1f8c9e93cfeb16fef59f56424ccc47b5a2a06e", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Tinydb10644a0e", + "profile_lines": [ + 1020, + 1023 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "upstream_repo": "msiemens/tinydb" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "b653b74b297bbd1afa0022c49abd39a2210b3c405da9af547d44228865957d8b", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/msiemens__tinydb.10644a0e.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install 'pytest>=7.2,<8' 'pytest-cov>=4,<5'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4318e4525086b9ab07b2269c7a6f1ff2003ad01a663b94f56e772d63655166be", + "pytest.ini": "2c2ccbf97dabef288fd402c4bb1ddba4d3baa35d1f903a3f5735633c1d504b7c" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "d2a682e33cab3a647d192896df452180d92928e9", + "source_completion_sha256": "b53fb28ef57a82a27b73ed00b42514a40f4930043ebe363e3b9a9cacfc6759be", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:msiemens__tinydb.10644a0e.combine_file__07uxvexn", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "278700580526dd378f18f40b641885ec78df63e1", + "instruction_sha256": "82799d50bb0a89ba9c23f8973ec88166005806aa40293ce16293fe51e69f45b9", + "is_fork": true, + "learner_path": "tasks/6a86a050b395ba9489ffc5ed/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "actual_upstream_url": "https://raw.githubusercontent.com/msiemens/tinydb/10644a0e07ad180c5b756aba272ee6b0dbd12df8/LICENSE", + "reviewed": true, + "sha256": "b0e2a2d39271e3d96b717d7be8235ac413d74797bf7f742f0801cfaad6c8c912", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/msiemens__tinydb.10644a0e/d2a682e33cab3a647d192896df452180d92928e9/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "patch_sha256": "a1ec8a26cc17f9786f5babcd5ad58e788150305bfa37c3f6f824cfcab0c7e302", + "provenance_path": "tasks/6a86a050b395ba9489ffc5ed/source-proof.json", + "repository_lineage": [ + "swesmith/msiemens__tinydb.10644a0e", + "msiemens/tinydb" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d2a682e33cab3a647d192896df452180d92928e9", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "875fe17e6e1f65d5e95e765cd006dd4ad30b71bb", + "source_kind": "mutation", + "source_repo": "swesmith/msiemens__tinydb.10644a0e", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "msiemens__tinydb.10644a0e.combine_file__07uxvexn", + "task_sha256": "9c6b3b3effea9534ca56530d93411e03dfd437218174ac954c6cfe13ca88b9a3", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "msiemens/tinydb", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/msiemens__tinydb.10644a0e", + "symlink_submodule_changes_supported": false, + "task_id": "msiemens__tinydb.10644a0e.combine_file__07uxvexn", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "msiemens/tinydb" +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/dependency-setup.sh b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..29ebee9df8beca1bfebc8b30cd7cb1dfc3cbf375 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/dependency-setup.sh @@ -0,0 +1,17 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +/usr/bin/sha256sum --check <<'OPENENV_NATIVE_TEST_REQUIREMENT' +4318e4525086b9ab07b2269c7a6f1ff2003ad01a663b94f56e772d63655166be pyproject.toml +OPENENV_NATIVE_TEST_REQUIREMENT +python -m pip install -e . +python -m pip install 'pytest>=7.2,<8' 'pytest-cov>=4,<5' + +cat > /tmp/openenv-tinydb-yaml.txt <<'OPENENV_PYYAML_PIN' +PyYAML==6.0.3 --hash=sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b +OPENENV_PYYAML_PIN +python -m pip install --no-deps --only-binary=:all: --require-hashes --index-url https://pypi.org/simple -r /tmp/openenv-tinydb-yaml.txt +python -c 'import yaml; assert yaml.__version__ == "6.0.3"' diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/environment/Dockerfile b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/instruction.md b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af7dfc4ec112be538712eeed143fbfc0f54f25eb --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/instruction.md @@ -0,0 +1,52 @@ +LRUCache get method breaks cache ordering and __len__ returns incorrect value + +#### Description + +The LRUCache implementation has issues with the `get` method and `__len__` method that cause cache operations to fail. + +#### Steps/Code to Reproduce + +```python +from tinydb.utils import LRUCache + +# Test 1: get method breaks cache +cache = LRUCache(capacity=3) +cache['a'] = 1 +cache['b'] = 2 +cache['c'] = 3 +_ = cache['a'] # This should move 'a' to end +cache['d'] = 4 +try: + _ = cache['f'] +except KeyError: + pass +print(cache.lru) # Expected: ['c', 'a', 'd'], but fails + +# Test 2: __len__ returns wrong value +cache = LRUCache(capacity=2) +cache['x'] = 1 +print(len(cache)) # Expected: 1, but returns 0 +``` + +Also affects TinyDB query caching: + +```python +from tinydb import TinyDB +from tinydb.queries import where +from tinydb.storages import MemoryStorage + +db = TinyDB(storage=MemoryStorage) +db.insert({'int': 1}) +db.insert({'int': 2}) +db.insert({'int': 3}) + +# This will fail due to LRUCache issues +results = db.search(where('int') == 1) +print(len(db._query_cache)) # Should be 1 but fails +``` + +The cache's `get` method and length calculation are not working correctly, causing various database operations that rely on caching to fail. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/metadata.json b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..8c79fdddbda9fe4b7fca286c5a4f1c72fc6f8008 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/metadata.json @@ -0,0 +1,386 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Tinydb10644a0e", + "profile_lines": [ + 1020, + 1023 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "upstream_repo": "msiemens/tinydb" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_tables.py::test_query_cache_with_mutable_callable[memory]", + "tests/test_tables.py::test_query_cache_with_mutable_callable[json]", + "tests/test_tables.py::test_zero_cache_size[memory]", + "tests/test_tables.py::test_zero_cache_size[json]", + "tests/test_tables.py::test_query_cache_size[memory]", + "tests/test_tables.py::test_query_cache_size[json]", + "tests/test_tables.py::test_lru_cache[memory]", + "tests/test_tables.py::test_lru_cache[json]", + "tests/test_tinydb.py::test_search[memory]", + "tests/test_tinydb.py::test_search[json]", + "tests/test_tinydb.py::test_search_path[memory]", + "tests/test_tinydb.py::test_search_path[json]", + "tests/test_tinydb.py::test_query_cache", + "tests/test_tinydb.py::test_lambda_query", + "tests/test_utils.py::test_lru_cache", + "tests/test_utils.py::test_lru_cache_set_update", + "tests/test_utils.py::test_freeze" + ], + "PASS_TO_PASS": [ + "tests/test_middlewares.py::test_caching", + "tests/test_middlewares.py::test_caching_read", + "tests/test_middlewares.py::test_caching_write_many", + "tests/test_middlewares.py::test_caching_flush", + "tests/test_middlewares.py::test_caching_flush_manually", + "tests/test_middlewares.py::test_caching_write", + "tests/test_middlewares.py::test_nested", + "tests/test_middlewares.py::test_caching_json_write", + "tests/test_operations.py::test_delete[memory]", + "tests/test_operations.py::test_delete[json]", + "tests/test_operations.py::test_add_int[memory]", + "tests/test_operations.py::test_add_int[json]", + "tests/test_operations.py::test_add_str[memory]", + "tests/test_operations.py::test_add_str[json]", + "tests/test_operations.py::test_subtract[memory]", + "tests/test_operations.py::test_subtract[json]", + "tests/test_operations.py::test_set[memory]", + "tests/test_operations.py::test_set[json]", + "tests/test_operations.py::test_increment[memory]", + "tests/test_operations.py::test_increment[json]", + "tests/test_operations.py::test_decrement[memory]", + "tests/test_operations.py::test_decrement[json]", + "tests/test_queries.py::test_no_path", + "tests/test_queries.py::test_path_exists", + "tests/test_queries.py::test_path_and", + "tests/test_queries.py::test_callable_in_path_with_map", + "tests/test_queries.py::test_callable_in_path_with_chain", + "tests/test_queries.py::test_eq", + "tests/test_queries.py::test_ne", + "tests/test_queries.py::test_lt", + "tests/test_queries.py::test_le", + "tests/test_queries.py::test_gt", + "tests/test_queries.py::test_ge", + "tests/test_queries.py::test_or", + "tests/test_queries.py::test_and", + "tests/test_queries.py::test_not", + "tests/test_queries.py::test_has_key", + "tests/test_queries.py::test_regex", + "tests/test_queries.py::test_custom", + "tests/test_queries.py::test_custom_with_params", + "tests/test_queries.py::test_any", + "tests/test_queries.py::test_all", + "tests/test_queries.py::test_has", + "tests/test_queries.py::test_one_of", + "tests/test_queries.py::test_hash", + "tests/test_queries.py::test_orm_usage", + "tests/test_queries.py::test_repr", + "tests/test_queries.py::test_subclass", + "tests/test_queries.py::test_noop", + "tests/test_queries.py::test_equality", + "tests/test_queries.py::test_empty_query_error", + "tests/test_queries.py::test_fragment", + "tests/test_queries.py::test_fragment_with_path", + "tests/test_queries.py::test_get_item", + "tests/test_storages.py::test_json", + "tests/test_storages.py::test_json_kwargs", + "tests/test_storages.py::test_json_readwrite", + "tests/test_storages.py::test_json_read", + "tests/test_storages.py::test_create_dirs", + "tests/test_storages.py::test_json_invalid_directory", + "tests/test_storages.py::test_in_memory", + "tests/test_storages.py::test_in_memory_close", + "tests/test_storages.py::test_custom", + "tests/test_storages.py::test_read_once", + "tests/test_storages.py::test_custom_with_exception", + "tests/test_storages.py::test_yaml", + "tests/test_storages.py::test_encoding", + "tests/test_tables.py::test_next_id[memory]", + "tests/test_tables.py::test_next_id[json]", + "tests/test_tables.py::test_tables_list[memory]", + "tests/test_tables.py::test_tables_list[json]", + "tests/test_tables.py::test_one_table[memory]", + "tests/test_tables.py::test_one_table[json]", + "tests/test_tables.py::test_multiple_tables[memory]", + "tests/test_tables.py::test_multiple_tables[json]", + "tests/test_tables.py::test_caching[memory]", + "tests/test_tables.py::test_caching[json]", + "tests/test_tables.py::test_query_cache[memory]", + "tests/test_tables.py::test_query_cache[json]", + "tests/test_tables.py::test_table_is_iterable[memory]", + "tests/test_tables.py::test_table_is_iterable[json]", + "tests/test_tables.py::test_table_name[memory]", + "tests/test_tables.py::test_table_name[json]", + "tests/test_tables.py::test_table_repr[memory]", + "tests/test_tables.py::test_table_repr[json]", + "tests/test_tables.py::test_truncate_table[memory]", + "tests/test_tables.py::test_truncate_table[json]", + "tests/test_tables.py::test_persist_table[memory]", + "tests/test_tables.py::test_persist_table[json]", + "tests/test_tinydb.py::test_drop_tables[memory]", + "tests/test_tinydb.py::test_drop_tables[json]", + "tests/test_tinydb.py::test_all[memory]", + "tests/test_tinydb.py::test_all[json]", + "tests/test_tinydb.py::test_insert[memory]", + "tests/test_tinydb.py::test_insert[json]", + "tests/test_tinydb.py::test_insert_ids[memory]", + "tests/test_tinydb.py::test_insert_ids[json]", + "tests/test_tinydb.py::test_insert_with_doc_id[memory]", + "tests/test_tinydb.py::test_insert_with_doc_id[json]", + "tests/test_tinydb.py::test_insert_with_duplicate_doc_id[memory]", + "tests/test_tinydb.py::test_insert_with_duplicate_doc_id[json]", + "tests/test_tinydb.py::test_insert_multiple[memory]", + "tests/test_tinydb.py::test_insert_multiple[json]", + "tests/test_tinydb.py::test_insert_multiple_with_ids[memory]", + "tests/test_tinydb.py::test_insert_multiple_with_ids[json]", + "tests/test_tinydb.py::test_insert_multiple_with_doc_ids[memory]", + "tests/test_tinydb.py::test_insert_multiple_with_doc_ids[json]", + "tests/test_tinydb.py::test_insert_invalid_type_raises_error[memory]", + "tests/test_tinydb.py::test_insert_invalid_type_raises_error[json]", + "tests/test_tinydb.py::test_insert_valid_mapping_type[memory]", + "tests/test_tinydb.py::test_insert_valid_mapping_type[json]", + "tests/test_tinydb.py::test_custom_mapping_type_with_json", + "tests/test_tinydb.py::test_remove[memory]", + "tests/test_tinydb.py::test_remove[json]", + "tests/test_tinydb.py::test_remove_all_fails[memory]", + "tests/test_tinydb.py::test_remove_all_fails[json]", + "tests/test_tinydb.py::test_remove_multiple[memory]", + "tests/test_tinydb.py::test_remove_multiple[json]", + "tests/test_tinydb.py::test_remove_ids[memory]", + "tests/test_tinydb.py::test_remove_ids[json]", + "tests/test_tinydb.py::test_remove_returns_ids[memory]", + "tests/test_tinydb.py::test_remove_returns_ids[json]", + "tests/test_tinydb.py::test_update[memory]", + "tests/test_tinydb.py::test_update[json]", + "tests/test_tinydb.py::test_update_all[memory]", + "tests/test_tinydb.py::test_update_all[json]", + "tests/test_tinydb.py::test_update_returns_ids[memory]", + "tests/test_tinydb.py::test_update_returns_ids[json]", + "tests/test_tinydb.py::test_update_transform[memory]", + "tests/test_tinydb.py::test_update_transform[json]", + "tests/test_tinydb.py::test_update_ids[memory]", + "tests/test_tinydb.py::test_update_ids[json]", + "tests/test_tinydb.py::test_update_multiple[memory]", + "tests/test_tinydb.py::test_update_multiple[json]", + "tests/test_tinydb.py::test_update_multiple_operation[memory]", + "tests/test_tinydb.py::test_update_multiple_operation[json]", + "tests/test_tinydb.py::test_upsert[memory]", + "tests/test_tinydb.py::test_upsert[json]", + "tests/test_tinydb.py::test_upsert_by_id[memory]", + "tests/test_tinydb.py::test_upsert_by_id[json]", + "tests/test_tinydb.py::test_search_no_results_cache[memory]", + "tests/test_tinydb.py::test_search_no_results_cache[json]", + "tests/test_tinydb.py::test_get[memory]", + "tests/test_tinydb.py::test_get[json]", + "tests/test_tinydb.py::test_get_ids[memory]", + "tests/test_tinydb.py::test_get_ids[json]", + "tests/test_tinydb.py::test_get_multiple_ids[memory]", + "tests/test_tinydb.py::test_get_multiple_ids[json]", + "tests/test_tinydb.py::test_get_invalid[memory]", + "tests/test_tinydb.py::test_get_invalid[json]", + "tests/test_tinydb.py::test_count[memory]", + "tests/test_tinydb.py::test_count[json]", + "tests/test_tinydb.py::test_contains[memory]", + "tests/test_tinydb.py::test_contains[json]", + "tests/test_tinydb.py::test_contains_ids[memory]", + "tests/test_tinydb.py::test_contains_ids[json]", + "tests/test_tinydb.py::test_contains_invalid[memory]", + "tests/test_tinydb.py::test_contains_invalid[json]", + "tests/test_tinydb.py::test_get_idempotent[memory]", + "tests/test_tinydb.py::test_get_idempotent[json]", + "tests/test_tinydb.py::test_multiple_dbs", + "tests/test_tinydb.py::test_storage_closed_once", + "tests/test_tinydb.py::test_unique_ids", + "tests/test_tinydb.py::test_lastid_after_open", + "tests/test_tinydb.py::test_doc_ids_json", + "tests/test_tinydb.py::test_insert_string", + "tests/test_tinydb.py::test_insert_invalid_dict", + "tests/test_tinydb.py::test_gc", + "tests/test_tinydb.py::test_drop_table", + "tests/test_tinydb.py::test_empty_write", + "tests/test_tinydb.py::test_tinydb_is_iterable[memory]", + "tests/test_tinydb.py::test_tinydb_is_iterable[json]", + "tests/test_tinydb.py::test_repr", + "tests/test_tinydb.py::test_delete", + "tests/test_tinydb.py::test_insert_multiple_with_single_dict[memory]", + "tests/test_tinydb.py::test_insert_multiple_with_single_dict[json]", + "tests/test_tinydb.py::test_access_storage", + "tests/test_tinydb.py::test_empty_db_len", + "tests/test_tinydb.py::test_insert_on_existing_db", + "tests/test_tinydb.py::test_storage_access", + "tests/test_utils.py::test_lru_cache_set_multiple", + "tests/test_utils.py::test_lru_cache_get", + "tests/test_utils.py::test_lru_cache_delete", + "tests/test_utils.py::test_lru_cache_clear", + "tests/test_utils.py::test_lru_cache_unlimited", + "tests/test_utils.py::test_lru_cache_unlimited_explicit", + "tests/test_utils.py::test_lru_cache_iteration_works" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "875fe17e6e1f65d5e95e765cd006dd4ad30b71bb", + "healthy": "278700580526dd378f18f40b641885ec78df63e1", + "learner": "d2a682e33cab3a647d192896df452180d92928e9" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.coveragerc", + "/testbed/.github/stale.yml", + "/testbed/.gitignore", + "/testbed/.readthedocs.yml", + "/testbed/CONTRIBUTING.rst", + "/testbed/LICENSE", + "/testbed/MANIFEST.in", + "/testbed/README.rst", + "/testbed/artwork/logo.png", + "/testbed/artwork/logo.svg", + "/testbed/docs/.gitignore", + "/testbed/docs/Makefile", + "/testbed/docs/_static/logo.png", + "/testbed/docs/_templates/links.html", + "/testbed/docs/_templates/sidebarlogo.html", + "/testbed/docs/_themes/.gitignore", + "/testbed/docs/_themes/LICENSE", + "/testbed/docs/_themes/README", + "/testbed/docs/_themes/flask/layout.html", + "/testbed/docs/_themes/flask/page.html", + "/testbed/docs/_themes/flask/relations.html", + "/testbed/docs/_themes/flask/static/flasky.css_t", + "/testbed/docs/_themes/flask/theme.conf", + "/testbed/docs/_themes/flask_theme_support.py", + "/testbed/docs/api.rst", + "/testbed/docs/changelog.rst", + "/testbed/docs/conf.py", + "/testbed/docs/contribute.rst", + "/testbed/docs/extend.rst", + "/testbed/docs/extensions.rst", + "/testbed/docs/getting-started.rst", + "/testbed/docs/index.rst", + "/testbed/docs/intro.rst", + "/testbed/docs/make.bat", + "/testbed/docs/upgrade.rst", + "/testbed/docs/usage.rst", + "/testbed/mypy.ini", + "/testbed/poetry.lock", + "/testbed/pyproject.toml", + "/testbed/pytest.ini", + "/testbed/tests/__init__.py", + "/testbed/tests/conftest.py", + "/testbed/tests/test_middlewares.py", + "/testbed/tests/test_operations.py", + "/testbed/tests/test_queries.py", + "/testbed/tests/test_storages.py", + "/testbed/tinydb/__init__.py", + "/testbed/tinydb/database.py", + "/testbed/tinydb/middlewares.py", + "/testbed/tinydb/mypy_plugin.py", + "/testbed/tinydb/operations.py", + "/testbed/tinydb/py.typed", + "/testbed/tinydb/queries.py", + "/testbed/tinydb/storages.py", + "/testbed/tinydb/table.py", + "/testbed/tinydb/utils.py", + "/testbed/tinydb/version.py" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Tinydb10644a0e", + "profile_lines": [ + 1020, + 1023 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "upstream_repo": "msiemens/tinydb" + }, + "original_source_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "private_test_paths": [ + "tests/test_tables.py", + "tests/test_tinydb.py", + "tests/test_utils.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "tinydb/utils.py" + ], + "source_repo": "swesmith/msiemens__tinydb.10644a0e", + "source_stages_bytes": 933523, + "task_id": "msiemens__tinydb.10644a0e.combine_file__07uxvexn", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "msiemens/tinydb" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:msiemens__tinydb.10644a0e.combine_file__07uxvexn", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "278700580526dd378f18f40b641885ec78df63e1", + "instruction_sha256": "82799d50bb0a89ba9c23f8973ec88166005806aa40293ce16293fe51e69f45b9", + "is_fork": true, + "learner_path": "tasks/6a86a050b395ba9489ffc5ed/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "actual_upstream_url": "https://raw.githubusercontent.com/msiemens/tinydb/10644a0e07ad180c5b756aba272ee6b0dbd12df8/LICENSE", + "reviewed": true, + "sha256": "b0e2a2d39271e3d96b717d7be8235ac413d74797bf7f742f0801cfaad6c8c912", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/msiemens__tinydb.10644a0e/d2a682e33cab3a647d192896df452180d92928e9/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "patch_sha256": "a1ec8a26cc17f9786f5babcd5ad58e788150305bfa37c3f6f824cfcab0c7e302", + "provenance_path": "tasks/6a86a050b395ba9489ffc5ed/source-proof.json", + "repository_lineage": [ + "swesmith/msiemens__tinydb.10644a0e", + "msiemens/tinydb" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d2a682e33cab3a647d192896df452180d92928e9", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "875fe17e6e1f65d5e95e765cd006dd4ad30b71bb", + "source_kind": "mutation", + "source_repo": "swesmith/msiemens__tinydb.10644a0e", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "msiemens__tinydb.10644a0e.combine_file__07uxvexn", + "task_sha256": "9c6b3b3effea9534ca56530d93411e03dfd437218174ac954c6cfe13ca88b9a3", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "msiemens/tinydb", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/provenance.json b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..247c9ff28dc7793f40c2c628fe3e1ddeb347b419 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "0b357f6329d9b7ad4a68c1e58e21acdadac483e41a4b99ccc738d0686b12ce1e", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "actual_upstream_url": "https://raw.githubusercontent.com/msiemens/tinydb/10644a0e07ad180c5b756aba272ee6b0dbd12df8/LICENSE", + "reviewed": true, + "sha256": "b0e2a2d39271e3d96b717d7be8235ac413d74797bf7f742f0801cfaad6c8c912", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/msiemens__tinydb.10644a0e/d2a682e33cab3a647d192896df452180d92928e9/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "b53fb28ef57a82a27b73ed00b42514a40f4930043ebe363e3b9a9cacfc6759be", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_proof_sha256": "5accb9c25de08a14fbc984878cd001b6ae1a8def6af94b13e21f37f3634847c3", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:msiemens__tinydb.10644a0e.combine_file__07uxvexn", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "278700580526dd378f18f40b641885ec78df63e1", + "instruction_sha256": "82799d50bb0a89ba9c23f8973ec88166005806aa40293ce16293fe51e69f45b9", + "is_fork": true, + "learner_path": "tasks/6a86a050b395ba9489ffc5ed/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "actual_upstream_url": "https://raw.githubusercontent.com/msiemens/tinydb/10644a0e07ad180c5b756aba272ee6b0dbd12df8/LICENSE", + "reviewed": true, + "sha256": "b0e2a2d39271e3d96b717d7be8235ac413d74797bf7f742f0801cfaad6c8c912", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/msiemens__tinydb.10644a0e/d2a682e33cab3a647d192896df452180d92928e9/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "patch_sha256": "a1ec8a26cc17f9786f5babcd5ad58e788150305bfa37c3f6f824cfcab0c7e302", + "provenance_path": "tasks/6a86a050b395ba9489ffc5ed/source-proof.json", + "repository_lineage": [ + "swesmith/msiemens__tinydb.10644a0e", + "msiemens/tinydb" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d2a682e33cab3a647d192896df452180d92928e9", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "875fe17e6e1f65d5e95e765cd006dd4ad30b71bb", + "source_kind": "mutation", + "source_repo": "swesmith/msiemens__tinydb.10644a0e", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "msiemens__tinydb.10644a0e.combine_file__07uxvexn", + "task_sha256": "9c6b3b3effea9534ca56530d93411e03dfd437218174ac954c6cfe13ca88b9a3", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "msiemens/tinydb", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "ff9a5ef814fab3aeaea8a510213b4330c9b7600d0e4cd9f29754ec6179c0d458" +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/provided-gold.diff b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..1f29b8ac8e1d4812508567e94d3026d810944887 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/provided-gold.diff @@ -0,0 +1,50 @@ +diff --git a/tinydb/utils.py b/tinydb/utils.py +index cb9fd37262ef447655b1c3fd39dfddec0aa525d9..e1f01fbc529856f87f4ff8c2eedc7b55561b69d1 100644 +--- a/tinydb/utils.py ++++ b/tinydb/utils.py +@@ -66,7 +66,7 @@ + self.cache.clear() + + def __len__(self) -> int: +- return self.length - 1 ++ return self.length + + def __contains__(self, key: object) -> bool: + return key in self.cache +@@ -88,10 +88,12 @@ + return iter(self.cache) + + def get(self, key: K, default: Optional[D] = None) -> Optional[Union[V, D]]: +- value = self.cache.pop(key, None) ++ value = self.cache.get(key) + + if value is not None: +- self.cache[key] = value ++ self.cache.move_to_end(key, last=True) ++ ++ return value + + return default + +@@ -123,9 +125,7 @@ + return hash(tuple(sorted(self.items()))) + + def _immutable(self, *args, **kws): +- if not args and not kws: +- return +- raise ValueError('object is immutable') ++ raise TypeError('object is immutable') + + # Disable write access to the dict + __setitem__ = _immutable +@@ -138,9 +138,7 @@ + raise TypeError('object is immutable') + + def pop(self, k, d=None): +- if d is not None: +- return d +- return None ++ raise TypeError('object is immutable') + + + def freeze(obj): diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/solution/solve.sh b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..989eb4d4e9573481c90227ed69fb9db98a869d2b --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/solution/solve.sh @@ -0,0 +1,56 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/tinydb/utils.py b/tinydb/utils.py +index cb9fd37262ef447655b1c3fd39dfddec0aa525d9..e1f01fbc529856f87f4ff8c2eedc7b55561b69d1 100644 +--- a/tinydb/utils.py ++++ b/tinydb/utils.py +@@ -66,7 +66,7 @@ + self.cache.clear() + + def __len__(self) -> int: +- return self.length - 1 ++ return self.length + + def __contains__(self, key: object) -> bool: + return key in self.cache +@@ -88,10 +88,12 @@ + return iter(self.cache) + + def get(self, key: K, default: Optional[D] = None) -> Optional[Union[V, D]]: +- value = self.cache.pop(key, None) ++ value = self.cache.get(key) + + if value is not None: +- self.cache[key] = value ++ self.cache.move_to_end(key, last=True) ++ ++ return value + + return default + +@@ -123,9 +125,7 @@ + return hash(tuple(sorted(self.items()))) + + def _immutable(self, *args, **kws): +- if not args and not kws: +- return +- raise ValueError('object is immutable') ++ raise TypeError('object is immutable') + + # Disable write access to the dict + __setitem__ = _immutable +@@ -138,9 +138,7 @@ + raise TypeError('object is immutable') + + def pop(self, k, d=None): +- if d is not None: +- return d +- return None ++ raise TypeError('object is immutable') + + + def freeze(obj): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/task.toml b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c2d1b74573d70368a6a7f98752758ef601ce4b8c --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:6dfe799a2cb2bee70cfd9c28548a407138baee691c9a014e8101ef771d4bb2b7" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/check_pytest.py b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/expected-panels.json b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..f1620eecf7e0667fd077d2cdf9aa1fe0f351bb37 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/expected-panels.json @@ -0,0 +1,210 @@ +{ + "fail-to-pass": [ + "tests/test_tables.py::test_query_cache_with_mutable_callable[memory]", + "tests/test_tables.py::test_query_cache_with_mutable_callable[json]", + "tests/test_tables.py::test_zero_cache_size[memory]", + "tests/test_tables.py::test_zero_cache_size[json]", + "tests/test_tables.py::test_query_cache_size[memory]", + "tests/test_tables.py::test_query_cache_size[json]", + "tests/test_tables.py::test_lru_cache[memory]", + "tests/test_tables.py::test_lru_cache[json]", + "tests/test_tinydb.py::test_search[memory]", + "tests/test_tinydb.py::test_search[json]", + "tests/test_tinydb.py::test_search_path[memory]", + "tests/test_tinydb.py::test_search_path[json]", + "tests/test_tinydb.py::test_query_cache", + "tests/test_tinydb.py::test_lambda_query", + "tests/test_utils.py::test_lru_cache", + "tests/test_utils.py::test_lru_cache_set_update", + "tests/test_utils.py::test_freeze" + ], + "pass-to-pass": [ + "tests/test_middlewares.py::test_caching", + "tests/test_middlewares.py::test_caching_read", + "tests/test_middlewares.py::test_caching_write_many", + "tests/test_middlewares.py::test_caching_flush", + "tests/test_middlewares.py::test_caching_flush_manually", + "tests/test_middlewares.py::test_caching_write", + "tests/test_middlewares.py::test_nested", + "tests/test_middlewares.py::test_caching_json_write", + "tests/test_operations.py::test_delete[memory]", + "tests/test_operations.py::test_delete[json]", + "tests/test_operations.py::test_add_int[memory]", + "tests/test_operations.py::test_add_int[json]", + "tests/test_operations.py::test_add_str[memory]", + "tests/test_operations.py::test_add_str[json]", + "tests/test_operations.py::test_subtract[memory]", + "tests/test_operations.py::test_subtract[json]", + "tests/test_operations.py::test_set[memory]", + "tests/test_operations.py::test_set[json]", + "tests/test_operations.py::test_increment[memory]", + "tests/test_operations.py::test_increment[json]", + "tests/test_operations.py::test_decrement[memory]", + "tests/test_operations.py::test_decrement[json]", + "tests/test_queries.py::test_no_path", + "tests/test_queries.py::test_path_exists", + "tests/test_queries.py::test_path_and", + "tests/test_queries.py::test_callable_in_path_with_map", + "tests/test_queries.py::test_callable_in_path_with_chain", + "tests/test_queries.py::test_eq", + "tests/test_queries.py::test_ne", + "tests/test_queries.py::test_lt", + "tests/test_queries.py::test_le", + "tests/test_queries.py::test_gt", + "tests/test_queries.py::test_ge", + "tests/test_queries.py::test_or", + "tests/test_queries.py::test_and", + "tests/test_queries.py::test_not", + "tests/test_queries.py::test_has_key", + "tests/test_queries.py::test_regex", + "tests/test_queries.py::test_custom", + "tests/test_queries.py::test_custom_with_params", + "tests/test_queries.py::test_any", + "tests/test_queries.py::test_all", + "tests/test_queries.py::test_has", + "tests/test_queries.py::test_one_of", + "tests/test_queries.py::test_hash", + "tests/test_queries.py::test_orm_usage", + "tests/test_queries.py::test_repr", + "tests/test_queries.py::test_subclass", + "tests/test_queries.py::test_noop", + "tests/test_queries.py::test_equality", + "tests/test_queries.py::test_empty_query_error", + "tests/test_queries.py::test_fragment", + "tests/test_queries.py::test_fragment_with_path", + "tests/test_queries.py::test_get_item", + "tests/test_storages.py::test_json", + "tests/test_storages.py::test_json_kwargs", + "tests/test_storages.py::test_json_readwrite", + "tests/test_storages.py::test_json_read", + "tests/test_storages.py::test_create_dirs", + "tests/test_storages.py::test_json_invalid_directory", + "tests/test_storages.py::test_in_memory", + "tests/test_storages.py::test_in_memory_close", + "tests/test_storages.py::test_custom", + "tests/test_storages.py::test_read_once", + "tests/test_storages.py::test_custom_with_exception", + "tests/test_storages.py::test_yaml", + "tests/test_storages.py::test_encoding", + "tests/test_tables.py::test_next_id[memory]", + "tests/test_tables.py::test_next_id[json]", + "tests/test_tables.py::test_tables_list[memory]", + "tests/test_tables.py::test_tables_list[json]", + "tests/test_tables.py::test_one_table[memory]", + "tests/test_tables.py::test_one_table[json]", + "tests/test_tables.py::test_multiple_tables[memory]", + "tests/test_tables.py::test_multiple_tables[json]", + "tests/test_tables.py::test_caching[memory]", + "tests/test_tables.py::test_caching[json]", + "tests/test_tables.py::test_query_cache[memory]", + "tests/test_tables.py::test_query_cache[json]", + "tests/test_tables.py::test_table_is_iterable[memory]", + "tests/test_tables.py::test_table_is_iterable[json]", + "tests/test_tables.py::test_table_name[memory]", + "tests/test_tables.py::test_table_name[json]", + "tests/test_tables.py::test_table_repr[memory]", + "tests/test_tables.py::test_table_repr[json]", + "tests/test_tables.py::test_truncate_table[memory]", + "tests/test_tables.py::test_truncate_table[json]", + "tests/test_tables.py::test_persist_table[memory]", + "tests/test_tables.py::test_persist_table[json]", + "tests/test_tinydb.py::test_drop_tables[memory]", + "tests/test_tinydb.py::test_drop_tables[json]", + "tests/test_tinydb.py::test_all[memory]", + "tests/test_tinydb.py::test_all[json]", + "tests/test_tinydb.py::test_insert[memory]", + "tests/test_tinydb.py::test_insert[json]", + "tests/test_tinydb.py::test_insert_ids[memory]", + "tests/test_tinydb.py::test_insert_ids[json]", + "tests/test_tinydb.py::test_insert_with_doc_id[memory]", + "tests/test_tinydb.py::test_insert_with_doc_id[json]", + "tests/test_tinydb.py::test_insert_with_duplicate_doc_id[memory]", + "tests/test_tinydb.py::test_insert_with_duplicate_doc_id[json]", + "tests/test_tinydb.py::test_insert_multiple[memory]", + "tests/test_tinydb.py::test_insert_multiple[json]", + "tests/test_tinydb.py::test_insert_multiple_with_ids[memory]", + "tests/test_tinydb.py::test_insert_multiple_with_ids[json]", + "tests/test_tinydb.py::test_insert_multiple_with_doc_ids[memory]", + "tests/test_tinydb.py::test_insert_multiple_with_doc_ids[json]", + "tests/test_tinydb.py::test_insert_invalid_type_raises_error[memory]", + "tests/test_tinydb.py::test_insert_invalid_type_raises_error[json]", + "tests/test_tinydb.py::test_insert_valid_mapping_type[memory]", + "tests/test_tinydb.py::test_insert_valid_mapping_type[json]", + "tests/test_tinydb.py::test_custom_mapping_type_with_json", + "tests/test_tinydb.py::test_remove[memory]", + "tests/test_tinydb.py::test_remove[json]", + "tests/test_tinydb.py::test_remove_all_fails[memory]", + "tests/test_tinydb.py::test_remove_all_fails[json]", + "tests/test_tinydb.py::test_remove_multiple[memory]", + "tests/test_tinydb.py::test_remove_multiple[json]", + "tests/test_tinydb.py::test_remove_ids[memory]", + "tests/test_tinydb.py::test_remove_ids[json]", + "tests/test_tinydb.py::test_remove_returns_ids[memory]", + "tests/test_tinydb.py::test_remove_returns_ids[json]", + "tests/test_tinydb.py::test_update[memory]", + "tests/test_tinydb.py::test_update[json]", + "tests/test_tinydb.py::test_update_all[memory]", + "tests/test_tinydb.py::test_update_all[json]", + "tests/test_tinydb.py::test_update_returns_ids[memory]", + "tests/test_tinydb.py::test_update_returns_ids[json]", + "tests/test_tinydb.py::test_update_transform[memory]", + "tests/test_tinydb.py::test_update_transform[json]", + "tests/test_tinydb.py::test_update_ids[memory]", + "tests/test_tinydb.py::test_update_ids[json]", + "tests/test_tinydb.py::test_update_multiple[memory]", + "tests/test_tinydb.py::test_update_multiple[json]", + "tests/test_tinydb.py::test_update_multiple_operation[memory]", + "tests/test_tinydb.py::test_update_multiple_operation[json]", + "tests/test_tinydb.py::test_upsert[memory]", + "tests/test_tinydb.py::test_upsert[json]", + "tests/test_tinydb.py::test_upsert_by_id[memory]", + "tests/test_tinydb.py::test_upsert_by_id[json]", + "tests/test_tinydb.py::test_search_no_results_cache[memory]", + "tests/test_tinydb.py::test_search_no_results_cache[json]", + "tests/test_tinydb.py::test_get[memory]", + "tests/test_tinydb.py::test_get[json]", + "tests/test_tinydb.py::test_get_ids[memory]", + "tests/test_tinydb.py::test_get_ids[json]", + "tests/test_tinydb.py::test_get_multiple_ids[memory]", + "tests/test_tinydb.py::test_get_multiple_ids[json]", + "tests/test_tinydb.py::test_get_invalid[memory]", + "tests/test_tinydb.py::test_get_invalid[json]", + "tests/test_tinydb.py::test_count[memory]", + "tests/test_tinydb.py::test_count[json]", + "tests/test_tinydb.py::test_contains[memory]", + "tests/test_tinydb.py::test_contains[json]", + "tests/test_tinydb.py::test_contains_ids[memory]", + "tests/test_tinydb.py::test_contains_ids[json]", + "tests/test_tinydb.py::test_contains_invalid[memory]", + "tests/test_tinydb.py::test_contains_invalid[json]", + "tests/test_tinydb.py::test_get_idempotent[memory]", + "tests/test_tinydb.py::test_get_idempotent[json]", + "tests/test_tinydb.py::test_multiple_dbs", + "tests/test_tinydb.py::test_storage_closed_once", + "tests/test_tinydb.py::test_unique_ids", + "tests/test_tinydb.py::test_lastid_after_open", + "tests/test_tinydb.py::test_doc_ids_json", + "tests/test_tinydb.py::test_insert_string", + "tests/test_tinydb.py::test_insert_invalid_dict", + "tests/test_tinydb.py::test_gc", + "tests/test_tinydb.py::test_drop_table", + "tests/test_tinydb.py::test_empty_write", + "tests/test_tinydb.py::test_tinydb_is_iterable[memory]", + "tests/test_tinydb.py::test_tinydb_is_iterable[json]", + "tests/test_tinydb.py::test_repr", + "tests/test_tinydb.py::test_delete", + "tests/test_tinydb.py::test_insert_multiple_with_single_dict[memory]", + "tests/test_tinydb.py::test_insert_multiple_with_single_dict[json]", + "tests/test_tinydb.py::test_access_storage", + "tests/test_tinydb.py::test_empty_db_len", + "tests/test_tinydb.py::test_insert_on_existing_db", + "tests/test_tinydb.py::test_storage_access", + "tests/test_utils.py::test_lru_cache_set_multiple", + "tests/test_utils.py::test_lru_cache_get", + "tests/test_utils.py::test_lru_cache_delete", + "tests/test_utils.py::test_lru_cache_clear", + "tests/test_utils.py::test_lru_cache_unlimited", + "tests/test_utils.py::test_lru_cache_unlimited_explicit", + "tests/test_utils.py::test_lru_cache_iteration_works" + ] +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/grade.py b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/panel-config.json b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..d9314376e51e1a2b862751e17bcc1da621853309 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/panel-config.json @@ -0,0 +1,23 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install 'pytest>=7.2,<8' 'pytest-cov>=4,<5'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4318e4525086b9ab07b2269c7a6f1ff2003ad01a663b94f56e772d63655166be", + "pytest.ini": "2c2ccbf97dabef288fd402c4bb1ddba4d3baa35d1f903a3f5735633c1d504b7c" + } +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/test.sh b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted-inventory.json b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..e3f7747a66be371780111d5bf493d9b1ca6fe41b --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted-inventory.json @@ -0,0 +1,62 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 1846, + "mode": 420, + "sha256": "4318e4525086b9ab07b2269c7a6f1ff2003ad01a663b94f56e772d63655166be" + }, + "pytest.ini": { + "bytes": 70, + "mode": 420, + "sha256": "2c2ccbf97dabef288fd402c4bb1ddba4d3baa35d1f903a3f5735633c1d504b7c" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/conftest.py": { + "bytes": 625, + "mode": 420, + "sha256": "502596fae1843322ec533028a76474d39e6fb70587a5749d8c9dd734b35e625b" + }, + "tests/test_middlewares.py": { + "bytes": 2412, + "mode": 420, + "sha256": "85a748d3d10e7be042ed37318153a6b79c7913a5d9536cad406ccccad380577b" + }, + "tests/test_operations.py": { + "bytes": 1021, + "mode": 420, + "sha256": "6313d342626a12973a5532b0b9344c5a30a959d7bfa4f6ca07d147317aee469e" + }, + "tests/test_queries.py": { + "bytes": 12331, + "mode": 420, + "sha256": "7978c6220a192f4256018bf37d76e6b4c644a962fed4d6fca7d8594b2cf63a49" + }, + "tests/test_storages.py": { + "bytes": 6489, + "mode": 420, + "sha256": "d74695d20e1d1742fa558da49bc2df8e84ca34e64e001070cbccce215bd39fa2" + }, + "tests/test_tables.py": { + "bytes": 4109, + "mode": 420, + "sha256": "f018615899e7c9c813aba0820c639f9402d3c9865a376eedaf9dc3ee89b85ef3" + }, + "tests/test_tinydb.py": { + "bytes": 18110, + "mode": 420, + "sha256": "d106d5e94536afe8416c1b8b01bc63381abb97f81a6a120743e7e1963b07b1d1" + }, + "tests/test_utils.py": { + "bytes": 2257, + "mode": 420, + "sha256": "659bd414226988e81d2811259c112676aa6bdfa3b9fb6fed4631030ae6d73f2e" + } + } +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/pyproject.toml b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..1cd4da1e6719a2d3895c33b51dab148a4b60dde3 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/pyproject.toml @@ -0,0 +1,61 @@ +[tool.poetry] +name = "tinydb" +version = "4.8.2" +description = "TinyDB is a tiny, document oriented database optimized for your happiness :)" +authors = ["Markus Siemens "] +license = "MIT" + +readme = "README.rst" + +homepage = "https://github.com/msiemens/tinydb" +documentation = "https://tinydb.readthedocs.org/" + +keywords = ["database", "nosql"] + +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Intended Audience :: System Administrators", + "License :: OSI Approved :: MIT License", + "Topic :: Database", + "Topic :: Database :: Database Engines/Servers", + "Topic :: Utilities", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Operating System :: OS Independent", + "Typing :: Typed", +] + +packages = [ + { include = "tinydb" }, + { include = "tests", format = "sdist" } +] + +[tool.poetry.urls] +"Changelog" = "https://tinydb.readthedocs.io/en/latest/changelog.html" +"Issues" = "https://github.com/msiemens/tinydb/issues" + +[tool.poetry.dependencies] +python = "^3.8" + +[tool.poetry.dev-dependencies] +pytest = "^7.2.0" +pytest-pycodestyle = "^2.3.1" +pytest-cov = "^4.0.0" +pycodestyle = "^2.10.0" +sphinx = "^7.0.0" +coveralls = "^3.3.1" +pyyaml = "^6.0" +pytest-mypy = { version = "^0.10.2", markers = "platform_python_implementation != 'PyPy'" } +types-PyYAML = "^6.0.0" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/pytest.ini b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..45e8707db03d886e6ec161802ec3d96694a4a5a7 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +addopts=--verbose --cov-append --cov-report term --cov tinydb \ No newline at end of file diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/__init__.py b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/conftest.py b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..99c3eaf2505aa0da13eee34d9e0f664d9a2c8b0e --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/conftest.py @@ -0,0 +1,27 @@ +import os.path +import tempfile +from pathlib import Path + +import pytest # type: ignore + +from tinydb.middlewares import CachingMiddleware +from tinydb.storages import MemoryStorage +from tinydb import TinyDB, JSONStorage + + +@pytest.fixture(params=['memory', 'json']) +def db(request, tmp_path: Path): + if request.param == 'json': + db_ = TinyDB(tmp_path / 'test.db', storage=JSONStorage) + else: + db_ = TinyDB(storage=MemoryStorage) + + db_.drop_tables() + db_.insert_multiple({'int': 1, 'char': c} for c in 'abc') + + yield db_ + + +@pytest.fixture +def storage(): + return CachingMiddleware(MemoryStorage)() diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_middlewares.py b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_middlewares.py new file mode 100644 index 0000000000000000000000000000000000000000..81a211950d37ae25078fdddb97381c9d7385fad8 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_middlewares.py @@ -0,0 +1,105 @@ +import os + +from tinydb import TinyDB +from tinydb.middlewares import CachingMiddleware +from tinydb.storages import MemoryStorage, JSONStorage + +doc = {'none': [None, None], 'int': 42, 'float': 3.1415899999999999, + 'list': ['LITE', 'RES_ACID', 'SUS_DEXT'], + 'dict': {'hp': 13, 'sp': 5}, + 'bool': [True, False, True, False]} + + +def test_caching(storage): + # Write contents + storage.write(doc) + + # Verify contents + assert doc == storage.read() + + +def test_caching_read(): + db = TinyDB(storage=CachingMiddleware(MemoryStorage)) + assert db.all() == [] + + +def test_caching_write_many(storage): + storage.WRITE_CACHE_SIZE = 3 + + # Storage should be still empty + assert storage.memory is None + + # Write contents + for x in range(2): + storage.write(doc) + assert storage.memory is None # Still cached + + storage.write(doc) + + # Verify contents: Cache should be emptied and written to storage + assert storage.memory + + +def test_caching_flush(storage): + # Write contents + for _ in range(CachingMiddleware.WRITE_CACHE_SIZE - 1): + storage.write(doc) + + # Not yet flushed... + assert storage.memory is None + + storage.write(doc) + + # Verify contents: Cache should be emptied and written to storage + assert storage.memory + + +def test_caching_flush_manually(storage): + # Write contents + storage.write(doc) + + storage.flush() + + # Verify contents: Cache should be emptied and written to storage + assert storage.memory + + +def test_caching_write(storage): + # Write contents + storage.write(doc) + + storage.close() + + # Verify contents: Cache should be emptied and written to storage + assert storage.storage.memory + + +def test_nested(): + storage = CachingMiddleware(MemoryStorage) + storage() # Initialization + + # Write contents + storage.write(doc) + + # Verify contents + assert doc == storage.read() + + +def test_caching_json_write(tmpdir): + path = str(tmpdir.join('test.db')) + + with TinyDB(path, storage=CachingMiddleware(JSONStorage)) as db: + db.insert({'key': 'value'}) + + # Verify database filesize + statinfo = os.stat(path) + assert statinfo.st_size != 0 + + # Assert JSON file has been closed + assert db._storage._handle.closed + + del db + + # Reopen database + with TinyDB(path, storage=CachingMiddleware(JSONStorage)) as db: + assert db.all() == [{'key': 'value'}] diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_operations.py b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..3a6f814f6ac61cea8684c373a413ff5aa9f7ae0c --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_operations.py @@ -0,0 +1,37 @@ +from tinydb import where +from tinydb.operations import delete, increment, decrement, add, subtract, set + + +def test_delete(db): + db.update(delete('int'), where('char') == 'a') + assert 'int' not in db.get(where('char') == 'a') + + +def test_add_int(db): + db.update(add('int', 5), where('char') == 'a') + assert db.get(where('char') == 'a')['int'] == 6 + + +def test_add_str(db): + db.update(add('char', 'xyz'), where('char') == 'a') + assert db.get(where('char') == 'axyz')['int'] == 1 + + +def test_subtract(db): + db.update(subtract('int', 5), where('char') == 'a') + assert db.get(where('char') == 'a')['int'] == -4 + + +def test_set(db): + db.update(set('char', 'xyz'), where('char') == 'a') + assert db.get(where('char') == 'xyz')['int'] == 1 + + +def test_increment(db): + db.update(increment('int'), where('char') == 'a') + assert db.get(where('char') == 'a')['int'] == 2 + + +def test_decrement(db): + db.update(decrement('int'), where('char') == 'a') + assert db.get(where('char') == 'a')['int'] == 0 diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_queries.py b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_queries.py new file mode 100644 index 0000000000000000000000000000000000000000..6e0dd8faa974a01cc23722c5d0d316a7d0a37193 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_queries.py @@ -0,0 +1,445 @@ +import re + +import pytest + +from tinydb.queries import Query, where + + +def test_no_path(): + with pytest.raises(ValueError): + _ = Query() == 2 + + +def test_path_exists(): + query = Query()['value'].exists() + assert query == where('value').exists() + assert query({'value': 1}) + assert not query({'something': 1}) + assert hash(query) + assert hash(query) != hash(where('asd')) + + query = Query()['value']['val'].exists() + assert query == where('value')['val'].exists() + assert query({'value': {'val': 2}}) + assert not query({'value': 1}) + assert not query({'value': {'asd': 1}}) + assert not query({'something': 1}) + assert hash(query) + assert hash(query) != hash(where('asd')) + + +def test_path_and(): + query = Query()['value'].exists() & (Query()['value'] == 5) + assert query({'value': 5}) + assert not query({'value': 10}) + assert not query({'something': 1}) + assert hash(query) + assert hash(query) != hash(where('value')) + + +def test_callable_in_path_with_map(): + double = lambda x: x + x + query = Query().value.map(double) == 10 + assert query({'value': 5}) + assert not query({'value': 10}) + + +def test_callable_in_path_with_chain(): + rekey = lambda x: {'y': x['a'], 'z': x['b']} + query = Query().map(rekey).z == 10 + assert query({'a': 5, 'b': 10}) + + +def test_eq(): + query = Query().value == 1 + assert query({'value': 1}) + assert not query({'value': 2}) + assert hash(query) + + query = Query().value == [0, 1] + assert query({'value': [0, 1]}) + assert not query({'value': [0, 1, 2]}) + assert hash(query) + + +def test_ne(): + query = Query().value != 1 + assert query({'value': 0}) + assert query({'value': 2}) + assert not query({'value': 1}) + assert hash(query) + + query = Query().value != [0, 1] + assert query({'value': [0, 1, 2]}) + assert not query({'value': [0, 1]}) + assert hash(query) + + +def test_lt(): + query = Query().value < 1 + assert query({'value': 0}) + assert not query({'value': 1}) + assert not query({'value': 2}) + assert hash(query) + + +def test_le(): + query = Query().value <= 1 + assert query({'value': 0}) + assert query({'value': 1}) + assert not query({'value': 2}) + assert hash(query) + + +def test_gt(): + query = Query().value > 1 + assert query({'value': 2}) + assert not query({'value': 1}) + assert hash(query) + + +def test_ge(): + query = Query().value >= 1 + assert query({'value': 2}) + assert query({'value': 1}) + assert not query({'value': 0}) + assert hash(query) + + +def test_or(): + query = ( + (Query().val1 == 1) | + (Query().val2 == 2) + ) + assert query({'val1': 1}) + assert query({'val2': 2}) + assert query({'val1': 1, 'val2': 2}) + assert not query({'val1': '', 'val2': ''}) + assert hash(query) + + +def test_and(): + query = ( + (Query().val1 == 1) & + (Query().val2 == 2) + ) + assert query({'val1': 1, 'val2': 2}) + assert not query({'val1': 1}) + assert not query({'val2': 2}) + assert not query({'val1': '', 'val2': ''}) + assert hash(query) + + +def test_not(): + query = ~ (Query().val1 == 1) + assert query({'val1': 5, 'val2': 2}) + assert not query({'val1': 1, 'val2': 2}) + assert hash(query) + + query = ( + (~ (Query().val1 == 1)) & + (Query().val2 == 2) + ) + assert query({'val1': '', 'val2': 2}) + assert query({'val2': 2}) + assert not query({'val1': 1, 'val2': 2}) + assert not query({'val1': 1}) + assert not query({'val1': '', 'val2': ''}) + assert hash(query) + + +def test_has_key(): + query = Query().val3.exists() + + assert query({'val3': 1}) + assert not query({'val1': 1, 'val2': 2}) + assert hash(query) + + +def test_regex(): + query = Query().val.matches(r'\d{2}\.') + + assert query({'val': '42.'}) + assert not query({'val': '44'}) + assert not query({'val': 'ab.'}) + assert not query({'val': 155}) + assert not query({'val': False}) + assert not query({'': None}) + assert hash(query) + + query = Query().val.search(r'\d+') + + assert query({'val': 'ab3'}) + assert not query({'val': 'abc'}) + assert not query({'val': ''}) + assert not query({'val': True}) + assert not query({'': None}) + assert hash(query) + + query = Query().val.search(r'JOHN', flags=re.IGNORECASE) + assert query({'val': 'john'}) + assert query({'val': 'xJohNx'}) + assert not query({'val': 'JOH'}) + assert not query({'val': 12}) + assert not query({'': None}) + assert hash(query) + + +def test_custom(): + def test(value): + return value == 42 + + query = Query().val.test(test) + + assert query({'val': 42}) + assert not query({'val': 40}) + assert not query({'val': '44'}) + assert not query({'': None}) + assert hash(query) + + def in_list(value, l): + return value in l + + query = Query().val.test(in_list, tuple([25, 35])) + assert not query({'val': 20}) + assert query({'val': 25}) + assert not query({'val': 30}) + assert query({'val': 35}) + assert not query({'val': 36}) + assert hash(query) + + +def test_custom_with_params(): + def test(value, minimum, maximum): + return minimum <= value <= maximum + + query = Query().val.test(test, 1, 10) + + assert query({'val': 5}) + assert not query({'val': 0}) + assert not query({'val': 11}) + assert not query({'': None}) + assert hash(query) + + +def test_any(): + query = Query().followers.any(Query().name == 'don') + + assert query({'followers': [{'name': 'don'}, {'name': 'john'}]}) + assert not query({'followers': 1}) + assert not query({}) + assert hash(query) + + query = Query().followers.any(Query().num.matches('\\d+')) + assert query({'followers': [{'num': '12'}, {'num': 'abc'}]}) + assert not query({'followers': [{'num': 'abc'}]}) + assert hash(query) + + query = Query().followers.any(['don', 'jon']) + assert query({'followers': ['don', 'greg', 'bill']}) + assert not query({'followers': ['greg', 'bill']}) + assert not query({}) + assert hash(query) + + query = Query().followers.any([{'name': 'don'}, {'name': 'john'}]) + assert query({'followers': [{'name': 'don'}, {'name': 'greg'}]}) + assert not query({'followers': [{'name': 'greg'}]}) + assert hash(query) + + +def test_all(): + query = Query().followers.all(Query().name == 'don') + assert query({'followers': [{'name': 'don'}]}) + assert not query({'followers': [{'name': 'don'}, {'name': 'john'}]}) + assert hash(query) + + query = Query().followers.all(Query().num.matches('\\d+')) + assert query({'followers': [{'num': '123'}, {'num': '456'}]}) + assert not query({'followers': [{'num': '123'}, {'num': 'abc'}]}) + assert hash(query) + + query = Query().followers.all(['don', 'john']) + assert query({'followers': ['don', 'john', 'greg']}) + assert not query({'followers': ['don', 'greg']}) + assert not query({}) + assert hash(query) + + query = Query().followers.all([{'name': 'jane'}, {'name': 'john'}]) + assert query({'followers': [{'name': 'john'}, {'name': 'jane'}]}) + assert query({'followers': [{'name': 'john'}, + {'name': 'jane'}, + {'name': 'bob'}]}) + assert not query({'followers': [{'name': 'john'}, {'name': 'bob'}]}) + assert hash(query) + + +def test_has(): + query = Query().key1.key2.exists() + str(query) # This used to cause a bug... + + assert query({'key1': {'key2': {'key3': 1}}}) + assert query({'key1': {'key2': 1}}) + assert not query({'key1': 3}) + assert not query({'key1': {'key1': 1}}) + assert not query({'key2': {'key1': 1}}) + assert hash(query) + + query = Query().key1.key2 == 1 + + assert query({'key1': {'key2': 1}}) + assert not query({'key1': {'key2': 2}}) + assert hash(query) + + # Nested has: key exists + query = Query().key1.key2.key3.exists() + assert query({'key1': {'key2': {'key3': 1}}}) + # Not a dict + assert not query({'key1': 1}) + assert not query({'key1': {'key2': 1}}) + # Wrong key + assert not query({'key1': {'key2': {'key0': 1}}}) + assert not query({'key1': {'key0': {'key3': 1}}}) + assert not query({'key0': {'key2': {'key3': 1}}}) + + assert hash(query) + + # Nested has: check for value + query = Query().key1.key2.key3 == 1 + assert query({'key1': {'key2': {'key3': 1}}}) + assert not query({'key1': {'key2': {'key3': 0}}}) + assert hash(query) + + # Test special methods: regex matches + query = Query().key1.value.matches(r'\d+') + assert query({'key1': {'value': '123'}}) + assert not query({'key2': {'value': '123'}}) + assert not query({'key2': {'value': 'abc'}}) + assert hash(query) + + # Test special methods: regex contains + query = Query().key1.value.search(r'\d+') + assert query({'key1': {'value': 'a2c'}}) + assert not query({'key2': {'value': 'a2c'}}) + assert not query({'key2': {'value': 'abc'}}) + assert hash(query) + + # Test special methods: nested has and regex matches + query = Query().key1.x.y.matches(r'\d+') + assert query({'key1': {'x': {'y': '123'}}}) + assert not query({'key1': {'x': {'y': 'abc'}}}) + assert hash(query) + + # Test special method: nested has and regex contains + query = Query().key1.x.y.search(r'\d+') + assert query({'key1': {'x': {'y': 'a2c'}}}) + assert not query({'key1': {'x': {'y': 'abc'}}}) + assert hash(query) + + # Test special methods: custom test + query = Query().key1.int.test(lambda x: x == 3) + assert query({'key1': {'int': 3}}) + assert hash(query) + + +def test_one_of(): + query = Query().key1.one_of(['value 1', 'value 2']) + assert query({'key1': 'value 1'}) + assert query({'key1': 'value 2'}) + assert not query({'key1': 'value 3'}) + + +def test_hash(): + d = { + Query().key1 == 2: True, + Query().key1.key2.key3.exists(): True, + Query().key1.exists() & Query().key2.exists(): True, + Query().key1.exists() | Query().key2.exists(): True, + } + + assert (Query().key1 == 2) in d + assert (Query().key1.key2.key3.exists()) in d + assert (Query()['key1.key2'].key3.exists()) not in d + + # Commutative property of & and | + assert (Query().key1.exists() & Query().key2.exists()) in d + assert (Query().key2.exists() & Query().key1.exists()) in d + assert (Query().key1.exists() | Query().key2.exists()) in d + assert (Query().key2.exists() | Query().key1.exists()) in d + + +def test_orm_usage(): + data = {'name': 'John', 'age': {'year': 2000}} + + User = Query() + query1 = User.name == 'John' + query2 = User.age.year == 2000 + assert query1(data) + assert query2(data) + + +def test_repr(): + Fruit = Query() + + assert repr(Fruit) == "Query()" + assert repr(Fruit.type == 'peach') == "QueryImpl('==', ('type',), 'peach')" + + +def test_subclass(): + # Test that a new query test method in a custom subclass is properly usable + class MyQueryClass(Query): + def equal_double(self, rhs): + return self._generate_test( + lambda value: value == rhs * 2, + ('equal_double', self._path, rhs) + ) + + query = MyQueryClass().val.equal_double('42') + + assert query({'val': '4242'}) + assert not query({'val': '42'}) + assert not query({'': None}) + assert hash(query) + + +def test_noop(): + query = Query().noop() + + assert query({'foo': True}) + assert query({'foo': None}) + assert query({}) + + +def test_equality(): + q = Query() + assert (q.foo == 2) != 0 + assert (q.foo == 'yes') != '' + + +def test_empty_query_error(): + with pytest.raises(RuntimeError, match='Empty query was evaluated'): + Query()({}) + + +def test_fragment(): + query = Query().fragment({'a': 4, 'b': True}) + + assert query({'a': 4, 'b': True, 'c': 'yes'}) + assert not query({'a': 4, 'c': 'yes'}) + assert not query({'b': True, 'c': 'yes'}) + assert not query({'a': 5, 'b': True, 'c': 'yes'}) + assert not query({'a': 4, 'b': 'no', 'c': 'yes'}) + + +def test_fragment_with_path(): + query = Query().doc.fragment({'a': 4, 'b': True}) + + assert query({'doc': {'a': 4, 'b': True, 'c': 'yes'}}) + assert not query({'a': 4, 'b': True, 'c': 'yes'}) + assert not query({'doc': {'a': 4, 'c': 'yes'}}) + + +def test_get_item(): + query = Query()['test'] == 1 + + assert query({'test': 1}) + assert not query({'test': 0}) diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_storages.py b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_storages.py new file mode 100644 index 0000000000000000000000000000000000000000..3cab11c3fe94d706234c5b125c2e7c430bbbf303 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_storages.py @@ -0,0 +1,281 @@ +import json +import os +import random +import tempfile + +import pytest + +from tinydb import TinyDB, where +from tinydb.storages import JSONStorage, MemoryStorage, Storage, touch +from tinydb.table import Document + +random.seed() + +doc = {'none': [None, None], 'int': 42, 'float': 3.1415899999999999, + 'list': ['LITE', 'RES_ACID', 'SUS_DEXT'], + 'dict': {'hp': 13, 'sp': 5}, + 'bool': [True, False, True, False]} + + +def test_json(tmpdir): + # Write contents + path = str(tmpdir.join('test.db')) + storage = JSONStorage(path) + storage.write(doc) + + # Verify contents + assert doc == storage.read() + storage.close() + + +def test_json_kwargs(tmpdir): + db_file = tmpdir.join('test.db') + db = TinyDB(str(db_file), sort_keys=True, indent=4, separators=(',', ': ')) + + # Write contents + db.insert({'b': 1}) + db.insert({'a': 1}) + + assert db_file.read() == '''{ + "_default": { + "1": { + "b": 1 + }, + "2": { + "a": 1 + } + } +}''' + db.close() + + +def test_json_readwrite(tmpdir): + """ + Regression test for issue #1 + """ + path = str(tmpdir.join('test.db')) + + # Create TinyDB instance + db = TinyDB(path, storage=JSONStorage) + + item = {'name': 'A very long entry'} + item2 = {'name': 'A short one'} + + def get(s): + return db.get(where('name') == s) + + db.insert(item) + assert get('A very long entry') == item + + db.remove(where('name') == 'A very long entry') + assert get('A very long entry') is None + + db.insert(item2) + assert get('A short one') == item2 + + db.remove(where('name') == 'A short one') + assert get('A short one') is None + + db.close() + + +def test_json_read(tmpdir): + r"""Open a database only for reading""" + path = str(tmpdir.join('test.db')) + with pytest.raises(FileNotFoundError): + db = TinyDB(path, storage=JSONStorage, access_mode='r') + # Create small database + db = TinyDB(path, storage=JSONStorage) + db.insert({'b': 1}) + db.insert({'a': 1}) + db.close() + # Access in read mode + db = TinyDB(path, storage=JSONStorage, access_mode='r') + assert db.get(where('a') == 1) == {'a': 1} # reading is fine + with pytest.raises(IOError): + db.insert({'c': 1}) # writing is not + db.close() + + +def test_create_dirs(): + temp_dir = tempfile.gettempdir() + + while True: + dname = os.path.join(temp_dir, str(random.getrandbits(20))) + if not os.path.exists(dname): + db_dir = dname + db_file = os.path.join(db_dir, 'db.json') + break + + with pytest.raises(IOError): + JSONStorage(db_file) + + JSONStorage(db_file, create_dirs=True).close() + assert os.path.exists(db_file) + + # Use create_dirs with already existing directory + JSONStorage(db_file, create_dirs=True).close() + assert os.path.exists(db_file) + + os.remove(db_file) + os.rmdir(db_dir) + + +def test_json_invalid_directory(): + with pytest.raises(IOError): + with TinyDB('/this/is/an/invalid/path/db.json', storage=JSONStorage): + pass + + +def test_in_memory(): + # Write contents + storage = MemoryStorage() + storage.write(doc) + + # Verify contents + assert doc == storage.read() + + # Test case for #21 + other = MemoryStorage() + other.write({}) + assert other.read() != storage.read() + + +def test_in_memory_close(): + with TinyDB(storage=MemoryStorage) as db: + db.insert({}) + + +def test_custom(): + # noinspection PyAbstractClass + class MyStorage(Storage): + pass + + with pytest.raises(TypeError): + MyStorage() + + +def test_read_once(): + count = 0 + + # noinspection PyAbstractClass + class MyStorage(Storage): + def __init__(self): + self.memory = None + + def read(self): + nonlocal count + count += 1 + + return self.memory + + def write(self, data): + self.memory = data + + with TinyDB(storage=MyStorage) as db: + assert count == 0 + + db.table(db.default_table_name) + + assert count == 0 + + db.all() + + assert count == 1 + + db.insert({'foo': 'bar'}) + + assert count == 3 # One for getting the next ID, one for the insert + + db.all() + + assert count == 4 + + +def test_custom_with_exception(): + class MyStorage(Storage): + def read(self): + pass + + def write(self, data): + pass + + def __init__(self): + raise ValueError() + + def close(self): + raise RuntimeError() + + with pytest.raises(ValueError): + with TinyDB(storage=MyStorage) as db: + pass + + +def test_yaml(tmpdir): + """ + :type tmpdir: py._path.local.LocalPath + """ + + try: + import yaml + except ImportError: + return pytest.skip('PyYAML not installed') + + def represent_doc(dumper, data): + # Represent `Document` objects as their dict's string representation + # which PyYAML understands + return dumper.represent_data(dict(data)) + + yaml.add_representer(Document, represent_doc) + + class YAMLStorage(Storage): + def __init__(self, filename): + self.filename = filename + touch(filename, False) + + def read(self): + with open(self.filename) as handle: + data = yaml.safe_load(handle.read()) + return data + + def write(self, data): + with open(self.filename, 'w') as handle: + yaml.dump(data, handle) + + def close(self): + pass + + # Write contents + path = str(tmpdir.join('test.db')) + db = TinyDB(path, storage=YAMLStorage) + db.insert(doc) + assert db.all() == [doc] + + db.update({'name': 'foo'}) + + assert '!' not in tmpdir.join('test.db').read() + + assert db.contains(where('name') == 'foo') + assert len(db) == 1 + + +def test_encoding(tmpdir): + japanese_doc = {"Test": u"こんにちは世界"} + + path = str(tmpdir.join('test.db')) + # cp936 is used for japanese encodings + jap_storage = JSONStorage(path, encoding="cp936") + jap_storage.write(japanese_doc) + + try: + exception = json.decoder.JSONDecodeError + except AttributeError: + exception = ValueError + + with pytest.raises(exception): + # cp037 is used for english encodings + eng_storage = JSONStorage(path, encoding="cp037") + eng_storage.read() + + jap_storage = JSONStorage(path, encoding="cp936") + assert japanese_doc == jap_storage.read() diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_tables.py b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_tables.py new file mode 100644 index 0000000000000000000000000000000000000000..4335200abaa2edd0b063bc6ac9943c0297589347 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_tables.py @@ -0,0 +1,179 @@ +import re + +import pytest + +from tinydb import where + + +def test_next_id(db): + db.truncate() + + assert db._get_next_id() == 1 + assert db._get_next_id() == 2 + assert db._get_next_id() == 3 + + +def test_tables_list(db): + db.table('table1').insert({'a': 1}) + db.table('table2').insert({'a': 1}) + + assert db.tables() == {'_default', 'table1', 'table2'} + + +def test_one_table(db): + table1 = db.table('table1') + + table1.insert_multiple({'int': 1, 'char': c} for c in 'abc') + + assert table1.get(where('int') == 1)['char'] == 'a' + assert table1.get(where('char') == 'b')['char'] == 'b' + + +def test_multiple_tables(db): + table1 = db.table('table1') + table2 = db.table('table2') + table3 = db.table('table3') + + table1.insert({'int': 1, 'char': 'a'}) + table2.insert({'int': 1, 'char': 'b'}) + table3.insert({'int': 1, 'char': 'c'}) + + assert table1.count(where('char') == 'a') == 1 + assert table2.count(where('char') == 'b') == 1 + assert table3.count(where('char') == 'c') == 1 + + db.drop_tables() + + assert len(table1) == 0 + assert len(table2) == 0 + assert len(table3) == 0 + + +def test_caching(db): + table1 = db.table('table1') + table2 = db.table('table1') + + assert table1 is table2 + + +def test_query_cache(db): + query1 = where('int') == 1 + + assert db.count(query1) == 3 + assert query1 in db._query_cache + + assert db.count(query1) == 3 + assert query1 in db._query_cache + + query2 = where('int') == 0 + + assert db.count(query2) == 0 + assert query2 in db._query_cache + + assert db.count(query2) == 0 + assert query2 in db._query_cache + + +def test_query_cache_with_mutable_callable(db): + table = db.table('table') + table.insert({'val': 5}) + + mutable = 5 + increase = lambda x: x + mutable + + assert where('val').is_cacheable() + assert not where('val').map(increase).is_cacheable() + assert not (where('val').map(increase) == 10).is_cacheable() + + search = where('val').map(increase) == 10 + assert table.count(search) == 1 + + # now `increase` would yield 15, not 10 + mutable = 10 + + assert table.count(search) == 0 + assert len(table._query_cache) == 0 + + +def test_zero_cache_size(db): + table = db.table('table3', cache_size=0) + query = where('int') == 1 + + table.insert({'int': 1}) + table.insert({'int': 1}) + + assert table.count(query) == 2 + assert table.count(where('int') == 2) == 0 + assert len(table._query_cache) == 0 + + +def test_query_cache_size(db): + table = db.table('table3', cache_size=1) + query = where('int') == 1 + + table.insert({'int': 1}) + table.insert({'int': 1}) + + assert table.count(query) == 2 + assert table.count(where('int') == 2) == 0 + assert len(table._query_cache) == 1 + + +def test_lru_cache(db): + # Test integration into TinyDB + table = db.table('table3', cache_size=2) + query = where('int') == 1 + + table.search(query) + table.search(where('int') == 2) + table.search(where('int') == 3) + assert query not in table._query_cache + + table.remove(where('int') == 1) + assert not table._query_cache.lru + + table.search(query) + + assert len(table._query_cache) == 1 + table.clear_cache() + assert len(table._query_cache) == 0 + + +def test_table_is_iterable(db): + table = db.table('table1') + + table.insert_multiple({'int': i} for i in range(3)) + + assert [r for r in table] == table.all() + + +def test_table_name(db): + name = 'table3' + table = db.table(name) + assert name == table.name + + with pytest.raises(AttributeError): + table.name = 'foo' + + +def test_table_repr(db): + name = 'table4' + table = db.table(name) + + assert re.match( + r"
>", + repr(table)) + + +def test_truncate_table(db): + db.truncate() + assert db._get_next_id() == 1 + + +def test_persist_table(db): + db.table("persisted", persist_empty=True) + assert "persisted" in db.tables() + + db.table("nonpersisted", persist_empty=False) + assert "nonpersisted" not in db.tables() diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_tinydb.py b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_tinydb.py new file mode 100644 index 0000000000000000000000000000000000000000..655027a5b2640113d24c572be6689aaf4fea3011 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_tinydb.py @@ -0,0 +1,716 @@ +import re +from collections.abc import Mapping + +import pytest + +from tinydb import TinyDB, where, Query +from tinydb.middlewares import Middleware, CachingMiddleware +from tinydb.storages import MemoryStorage, JSONStorage +from tinydb.table import Document + + +def test_drop_tables(db: TinyDB): + db.drop_tables() + + db.insert({}) + db.drop_tables() + + assert len(db) == 0 + + +def test_all(db: TinyDB): + db.drop_tables() + + for i in range(10): + db.insert({}) + + assert len(db.all()) == 10 + + +def test_insert(db: TinyDB): + db.drop_tables() + db.insert({'int': 1, 'char': 'a'}) + + assert db.count(where('int') == 1) == 1 + + db.drop_tables() + + db.insert({'int': 1, 'char': 'a'}) + db.insert({'int': 1, 'char': 'b'}) + db.insert({'int': 1, 'char': 'c'}) + + assert db.count(where('int') == 1) == 3 + assert db.count(where('char') == 'a') == 1 + + +def test_insert_ids(db: TinyDB): + db.drop_tables() + assert db.insert({'int': 1, 'char': 'a'}) == 1 + assert db.insert({'int': 1, 'char': 'a'}) == 2 + + +def test_insert_with_doc_id(db: TinyDB): + db.drop_tables() + assert db.insert({'int': 1, 'char': 'a'}) == 1 + assert db.insert(Document({'int': 1, 'char': 'a'}, 12)) == 12 + assert db.insert(Document({'int': 1, 'char': 'a'}, 77)) == 77 + assert db.insert({'int': 1, 'char': 'a'}) == 78 + + +def test_insert_with_duplicate_doc_id(db: TinyDB): + db.drop_tables() + assert db.insert({'int': 1, 'char': 'a'}) == 1 + + with pytest.raises(ValueError): + db.insert(Document({'int': 1, 'char': 'a'}, 1)) + + +def test_insert_multiple(db: TinyDB): + db.drop_tables() + assert not db.contains(where('int') == 1) + + # Insert multiple from list + db.insert_multiple([{'int': 1, 'char': 'a'}, + {'int': 1, 'char': 'b'}, + {'int': 1, 'char': 'c'}]) + + assert db.count(where('int') == 1) == 3 + assert db.count(where('char') == 'a') == 1 + + # Insert multiple from generator function + def generator(): + for j in range(10): + yield {'int': j} + + db.drop_tables() + + db.insert_multiple(generator()) + + for i in range(10): + assert db.count(where('int') == i) == 1 + assert db.count(where('int').exists()) == 10 + + # Insert multiple from inline generator + db.drop_tables() + + db.insert_multiple({'int': i} for i in range(10)) + + for i in range(10): + assert db.count(where('int') == i) == 1 + + +def test_insert_multiple_with_ids(db: TinyDB): + db.drop_tables() + + # Insert multiple from list + assert db.insert_multiple([{'int': 1, 'char': 'a'}, + {'int': 1, 'char': 'b'}, + {'int': 1, 'char': 'c'}]) == [1, 2, 3] + + +def test_insert_multiple_with_doc_ids(db: TinyDB): + db.drop_tables() + + assert db.insert_multiple([ + Document({'int': 1, 'char': 'a'}, 12), + Document({'int': 1, 'char': 'b'}, 77) + ]) == [12, 77] + assert db.get(doc_id=12) == {'int': 1, 'char': 'a'} + assert db.get(doc_id=77) == {'int': 1, 'char': 'b'} + + with pytest.raises(ValueError): + db.insert_multiple([Document({'int': 1, 'char': 'a'}, 12)]) + + +def test_insert_invalid_type_raises_error(db: TinyDB): + with pytest.raises(ValueError, match='Document is not a Mapping'): + # object() as an example of a non-mapping-type + db.insert(object()) # type: ignore + + +def test_insert_valid_mapping_type(db: TinyDB): + class CustomDocument(Mapping): + def __init__(self, data): + self.data = data + + def __getitem__(self, key): + return self.data[key] + + def __iter__(self): + return iter(self.data) + + def __len__(self): + return len(self.data) + + db.drop_tables() + db.insert(CustomDocument({'int': 1, 'char': 'a'})) + assert db.count(where('int') == 1) == 1 + + +def test_custom_mapping_type_with_json(tmpdir): + class CustomDocument(Mapping): + def __init__(self, data): + self.data = data + + def __getitem__(self, key): + return self.data[key] + + def __iter__(self): + return iter(self.data) + + def __len__(self): + return len(self.data) + + # Insert + db = TinyDB(str(tmpdir.join('test.db'))) + db.drop_tables() + db.insert(CustomDocument({'int': 1, 'char': 'a'})) + assert db.count(where('int') == 1) == 1 + + # Insert multiple + db.insert_multiple([ + CustomDocument({'int': 2, 'char': 'a'}), + CustomDocument({'int': 3, 'char': 'a'}) + ]) + assert db.count(where('int') == 1) == 1 + assert db.count(where('int') == 2) == 1 + assert db.count(where('int') == 3) == 1 + + # Write back + doc_id = db.get(where('int') == 3).doc_id + db.update(CustomDocument({'int': 4, 'char': 'a'}), doc_ids=[doc_id]) + assert db.count(where('int') == 3) == 0 + assert db.count(where('int') == 4) == 1 + + +def test_remove(db: TinyDB): + db.remove(where('char') == 'b') + + assert len(db) == 2 + assert db.count(where('int') == 1) == 2 + + +def test_remove_all_fails(db: TinyDB): + with pytest.raises(RuntimeError): + db.remove() + + +def test_remove_multiple(db: TinyDB): + db.remove(where('int') == 1) + + assert len(db) == 0 + + +def test_remove_ids(db: TinyDB): + db.remove(doc_ids=[1, 2]) + + assert len(db) == 1 + + +def test_remove_returns_ids(db: TinyDB): + assert db.remove(where('char') == 'b') == [2] + + +def test_update(db: TinyDB): + assert len(db) == 3 + + db.update({'int': 2}, where('char') == 'a') + + assert db.count(where('int') == 2) == 1 + assert db.count(where('int') == 1) == 2 + + +def test_update_all(db: TinyDB): + assert db.count(where('int') == 1) == 3 + + db.update({'newField': True}) + + assert db.count(where('newField') == True) == 3 # noqa + + +def test_update_returns_ids(db: TinyDB): + db.drop_tables() + assert db.insert({'int': 1, 'char': 'a'}) == 1 + assert db.insert({'int': 1, 'char': 'a'}) == 2 + + assert db.update({'char': 'b'}, where('int') == 1) == [1, 2] + + +def test_update_transform(db: TinyDB): + def increment(field): + def transform(el): + el[field] += 1 + + return transform + + def delete(field): + def transform(el): + del el[field] + + return transform + + assert db.count(where('int') == 1) == 3 + + db.update(increment('int'), where('char') == 'a') + db.update(delete('char'), where('char') == 'a') + + assert db.count(where('int') == 2) == 1 + assert db.count(where('char') == 'a') == 0 + assert db.count(where('int') == 1) == 2 + + +def test_update_ids(db: TinyDB): + db.update({'int': 2}, doc_ids=[1, 2]) + + assert db.count(where('int') == 2) == 2 + + +def test_update_multiple(db: TinyDB): + assert len(db) == 3 + + db.update_multiple([ + ({'int': 2}, where('char') == 'a'), + ({'int': 4}, where('char') == 'b'), + ]) + + assert db.count(where('int') == 1) == 1 + assert db.count(where('int') == 2) == 1 + assert db.count(where('int') == 4) == 1 + + +def test_update_multiple_operation(db: TinyDB): + def increment(field): + def transform(el): + el[field] += 1 + + return transform + + assert db.count(where('int') == 1) == 3 + + db.update_multiple([ + (increment('int'), where('char') == 'a'), + (increment('int'), where('char') == 'b') + ]) + + assert db.count(where('int') == 2) == 2 + + +def test_upsert(db: TinyDB): + assert len(db) == 3 + + # Document existing + db.upsert({'int': 5}, where('char') == 'a') + assert db.count(where('int') == 5) == 1 + + # Document missing + assert db.upsert({'int': 9, 'char': 'x'}, where('char') == 'x') == [4] + assert db.count(where('int') == 9) == 1 + + +def test_upsert_by_id(db: TinyDB): + assert len(db) == 3 + + # Single document existing + extant_doc = Document({'char': 'v'}, doc_id=1) + assert db.upsert(extant_doc) == [1] + doc = db.get(where('char') == 'v') + assert isinstance(doc, Document) + assert doc is not None + assert doc.doc_id == 1 + assert len(db) == 3 + + # Single document missing + missing_doc = Document({'int': 5, 'char': 'w'}, doc_id=5) + assert db.upsert(missing_doc) == [5] + doc = db.get(where('char') == 'w') + assert isinstance(doc, Document) + assert doc is not None + assert doc.doc_id == 5 + assert len(db) == 4 + + # Missing doc_id and condition + with pytest.raises(ValueError, match=r"(?=.*\bdoc_id\b)(?=.*\bquery\b)"): + db.upsert({'no_Document': 'no_query'}) + + # Make sure we didn't break anything + assert db.insert({'check': '_next_id'}) == 6 + + +def test_search(db: TinyDB): + assert not db._query_cache + assert len(db.search(where('int') == 1)) == 3 + + assert len(db._query_cache) == 1 + assert len(db.search(where('int') == 1)) == 3 # Query result from cache + + +def test_search_path(db: TinyDB): + assert not db._query_cache + assert len(db.search(where('int').exists())) == 3 + assert len(db._query_cache) == 1 + + assert len(db.search(where('asd').exists())) == 0 + assert len(db.search(where('int').exists())) == 3 # Query result from cache + + +def test_search_no_results_cache(db: TinyDB): + assert len(db.search(where('missing').exists())) == 0 + assert len(db.search(where('missing').exists())) == 0 + + +def test_get(db: TinyDB): + item = db.get(where('char') == 'b') + assert isinstance(item, Document) + assert item is not None + assert item['char'] == 'b' + + +def test_get_ids(db: TinyDB): + el = db.all()[0] + assert db.get(doc_id=el.doc_id) == el + assert db.get(doc_id=float('NaN')) is None # type: ignore + + +def test_get_multiple_ids(db: TinyDB): + el = db.all() + assert db.get(doc_ids=[x.doc_id for x in el]) == el + + +def test_get_invalid(db: TinyDB): + with pytest.raises(RuntimeError): + db.get() + + +def test_count(db: TinyDB): + assert db.count(where('int') == 1) == 3 + assert db.count(where('char') == 'd') == 0 + + +def test_contains(db: TinyDB): + assert db.contains(where('int') == 1) + assert not db.contains(where('int') == 0) + + +def test_contains_ids(db: TinyDB): + assert db.contains(doc_id=1) + assert db.contains(doc_id=2) + assert not db.contains(doc_id=88) + + +def test_contains_invalid(db: TinyDB): + with pytest.raises(RuntimeError): + db.contains() + + +def test_get_idempotent(db: TinyDB): + u = db.get(where('int') == 1) + z = db.get(where('int') == 1) + assert u == z + + +def test_multiple_dbs(): + """ + Regression test for issue #3 + """ + db1 = TinyDB(storage=MemoryStorage) + db2 = TinyDB(storage=MemoryStorage) + + db1.insert({'int': 1, 'char': 'a'}) + db1.insert({'int': 1, 'char': 'b'}) + db1.insert({'int': 1, 'value': 5.0}) + + db2.insert({'color': 'blue', 'animal': 'turtle'}) + + assert len(db1) == 3 + assert len(db2) == 1 + + +def test_storage_closed_once(): + class Storage: + def __init__(self): + self.closed = False + + def read(self): + return {} + + def write(self, data): + pass + + def close(self): + assert not self.closed + self.closed = True + + with TinyDB(storage=Storage) as db: + db.close() + + del db + # If db.close() is called during cleanup, the assertion will fail and throw + # and exception + + +def test_unique_ids(tmpdir): + """ + :type tmpdir: py._path.local.LocalPath + """ + path = str(tmpdir.join('db.json')) + + # Verify ids are unique when reopening the DB and inserting + with TinyDB(path) as _db: + _db.insert({'x': 1}) + + with TinyDB(path) as _db: + _db.insert({'x': 1}) + + with TinyDB(path) as _db: + data = _db.all() + + assert data[0].doc_id != data[1].doc_id + + # Verify ids stay unique when inserting/removing + with TinyDB(path) as _db: + _db.drop_tables() + _db.insert_multiple({'x': i} for i in range(5)) + _db.remove(where('x') == 2) + + assert len(_db) == 4 + + ids = [e.doc_id for e in _db.all()] + assert len(ids) == len(set(ids)) + + +def test_lastid_after_open(tmpdir): + """ + Regression test for issue #34 + + :type tmpdir: py._path.local.LocalPath + """ + + NUM = 100 + path = str(tmpdir.join('db.json')) + + with TinyDB(path) as _db: + _db.insert_multiple({'i': i} for i in range(NUM)) + + with TinyDB(path) as _db: + assert _db._get_next_id() - 1 == NUM + + +def test_doc_ids_json(tmpdir): + """ + Regression test for issue #45 + """ + + path = str(tmpdir.join('db.json')) + + with TinyDB(path) as _db: + _db.drop_tables() + assert _db.insert({'int': 1, 'char': 'a'}) == 1 + assert _db.insert({'int': 1, 'char': 'a'}) == 2 + + _db.drop_tables() + assert _db.insert_multiple([{'int': 1, 'char': 'a'}, + {'int': 1, 'char': 'b'}, + {'int': 1, 'char': 'c'}]) == [1, 2, 3] + + assert _db.contains(doc_id=1) + assert _db.contains(doc_id=2) + assert not _db.contains(doc_id=88) + + _db.update({'int': 2}, doc_ids=[1, 2]) + assert _db.count(where('int') == 2) == 2 + + el = _db.all()[0] + assert _db.get(doc_id=el.doc_id) == el + assert _db.get(doc_id=float('NaN')) is None + + _db.remove(doc_ids=[1, 2]) + assert len(_db) == 1 + + +def test_insert_string(tmpdir): + path = str(tmpdir.join('db.json')) + + with TinyDB(path) as _db: + data = [{'int': 1}, {'int': 2}] + _db.insert_multiple(data) + + with pytest.raises(ValueError): + _db.insert([1, 2, 3]) # Fails + + with pytest.raises(ValueError): + _db.insert({'bark'}) # Fails + + assert data == _db.all() + + _db.insert({'int': 3}) # Does not fail + + +def test_insert_invalid_dict(tmpdir): + path = str(tmpdir.join('db.json')) + + with TinyDB(path) as _db: + data = [{'int': 1}, {'int': 2}] + _db.insert_multiple(data) + + with pytest.raises(TypeError): + _db.insert({'int': _db}) # Fails + + assert data == _db.all() + + _db.insert({'int': 3}) # Does not fail + + +def test_gc(tmpdir): + # See https://github.com/msiemens/tinydb/issues/92 + path = str(tmpdir.join('db.json')) + db = TinyDB(path) + table = db.table('foo') + table.insert({'something': 'else'}) + table.insert({'int': 13}) + assert len(table.search(where('int') == 13)) == 1 + assert table.all() == [{'something': 'else'}, {'int': 13}] + db.close() + + +def test_drop_table(): + db = TinyDB(storage=MemoryStorage) + default_table_name = db.table(db.default_table_name).name + + assert [] == list(db.tables()) + db.drop_table(default_table_name) + + db.insert({'a': 1}) + assert [default_table_name] == list(db.tables()) + + db.drop_table(default_table_name) + assert [] == list(db.tables()) + + table_name = 'some-other-table' + db = TinyDB(storage=MemoryStorage) + db.table(table_name).insert({'a': 1}) + assert {table_name} == db.tables() + + db.drop_table(table_name) + assert set() == db.tables() + assert table_name not in db._tables + + db.drop_table('non-existent-table-name') + assert set() == db.tables() + + +def test_empty_write(tmpdir): + path = str(tmpdir.join('db.json')) + + class ReadOnlyMiddleware(Middleware): + def write(self, data): + raise AssertionError('No write for unchanged db') + + TinyDB(path).close() + TinyDB(path, storage=ReadOnlyMiddleware(JSONStorage)).close() + + +def test_query_cache(): + db = TinyDB(storage=MemoryStorage) + db.insert_multiple([ + {'name': 'foo', 'value': 42}, + {'name': 'bar', 'value': -1337} + ]) + + query = where('value') > 0 + + results = db.search(query) + assert len(results) == 1 + + # Modify the db instance to not return any results when + # bypassing the query cache + db._tables[db.table(db.default_table_name).name]._read_table = lambda: {} + + # Make sure we got an independent copy of the result list + results.extend([1]) + assert db.search(query) == [{'name': 'foo', 'value': 42}] + + +def test_tinydb_is_iterable(db: TinyDB): + assert [r for r in db] == db.all() + + +def test_repr(tmpdir): + path = str(tmpdir.join('db.json')) + + db = TinyDB(path) + db.insert({'a': 1}) + + assert re.match( + r"", + repr(db)) + + +def test_delete(tmpdir): + path = str(tmpdir.join('db.json')) + + db = TinyDB(path, ensure_ascii=False) + q = Query() + db.insert({'network': {'id': '114', 'name': 'ok', 'rpc': 'dac', + 'ticker': 'mkay'}}) + assert db.search(q.network.id == '114') == [ + {'network': {'id': '114', 'name': 'ok', 'rpc': 'dac', + 'ticker': 'mkay'}} + ] + db.remove(q.network.id == '114') + assert db.search(q.network.id == '114') == [] + + +def test_insert_multiple_with_single_dict(db: TinyDB): + with pytest.raises(ValueError): + d = {'first': 'John', 'last': 'smith'} + db.insert_multiple(d) # type: ignore + db.close() + + +def test_access_storage(): + assert isinstance(TinyDB(storage=MemoryStorage).storage, + MemoryStorage) + assert isinstance(TinyDB(storage=CachingMiddleware(MemoryStorage)).storage, + CachingMiddleware) + + +def test_empty_db_len(): + db = TinyDB(storage=MemoryStorage) + assert len(db) == 0 + + +def test_insert_on_existing_db(tmpdir): + path = str(tmpdir.join('db.json')) + + db = TinyDB(path, ensure_ascii=False) + db.insert({'foo': 'bar'}) + + assert len(db) == 1 + + db.close() + + db = TinyDB(path, ensure_ascii=False) + db.insert({'foo': 'bar'}) + db.insert({'foo': 'bar'}) + + assert len(db) == 3 + + +def test_storage_access(): + db = TinyDB(storage=MemoryStorage) + + assert isinstance(db.storage, MemoryStorage) + + +def test_lambda_query(): + db = TinyDB(storage=MemoryStorage) + db.insert({'foo': 'bar'}) + + query = lambda doc: doc.get('foo') == 'bar' + query.is_cacheable = lambda: False + assert db.search(query) == [{'foo': 'bar'}] + assert not db._query_cache diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_utils.py b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..031e086f6b91dc8e4959f6a3d62bdb9c1cf0687a --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/tests/trusted/tests/test_utils.py @@ -0,0 +1,116 @@ +import pytest + +from tinydb.utils import LRUCache, freeze, FrozenDict + + +def test_lru_cache(): + cache = LRUCache(capacity=3) + cache["a"] = 1 + cache["b"] = 2 + cache["c"] = 3 + _ = cache["a"] # move to front in lru queue + cache["d"] = 4 # move oldest item out of lru queue + + try: + _ = cache['f'] + except KeyError: + pass + + assert cache.lru == ["c", "a", "d"] + + +def test_lru_cache_set_multiple(): + cache = LRUCache(capacity=3) + cache["a"] = 1 + cache["a"] = 2 + cache["a"] = 3 + cache["a"] = 4 + + assert cache.lru == ["a"] + + +def test_lru_cache_set_update(): + cache = LRUCache(capacity=3) + cache["a"] = 1 + cache["a"] = 2 + + assert cache["a"] == 2 + + +def test_lru_cache_get(): + cache = LRUCache(capacity=3) + cache["a"] = 1 + cache["b"] = 1 + cache["c"] = 1 + cache.get("a") + cache["d"] = 4 + + assert cache.lru == ["c", "a", "d"] + + +def test_lru_cache_delete(): + cache = LRUCache(capacity=3) + cache["a"] = 1 + cache["b"] = 2 + del cache["a"] + + try: + del cache['f'] + except KeyError: + pass + + assert cache.lru == ["b"] + + +def test_lru_cache_clear(): + cache = LRUCache(capacity=3) + cache["a"] = 1 + cache["b"] = 2 + cache.clear() + + assert cache.lru == [] + + +def test_lru_cache_unlimited(): + cache = LRUCache() + for i in range(100): + cache[i] = i + + assert len(cache.lru) == 100 + + +def test_lru_cache_unlimited_explicit(): + cache = LRUCache(capacity=None) + for i in range(100): + cache[i] = i + + assert len(cache.lru) == 100 + + +def test_lru_cache_iteration_works(): + cache = LRUCache() + count = 0 + for _ in cache: + assert False, 'there should be no elements in the cache' + + assert count == 0 + + +def test_freeze(): + frozen = freeze([0, 1, 2, {'a': [1, 2, 3]}, {1, 2}]) + assert isinstance(frozen, tuple) + assert isinstance(frozen[3], FrozenDict) + assert isinstance(frozen[3]['a'], tuple) + assert isinstance(frozen[4], frozenset) + + with pytest.raises(TypeError): + frozen[0] = 10 + + with pytest.raises(TypeError): + frozen[3]['a'] = 10 + + with pytest.raises(TypeError): + frozen[3].pop('a') + + with pytest.raises(TypeError): + frozen[3].update({'a': 9}) diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/validation/canaries/first-hunk-only.sh b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..cf0c8a06b5f80895a6d3e118d5231c158ca22cbc --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/tinydb/utils.py b/tinydb/utils.py +index cb9fd37262ef447655b1c3fd39dfddec0aa525d9..e1f01fbc529856f87f4ff8c2eedc7b55561b69d1 100644 +--- a/tinydb/utils.py ++++ b/tinydb/utils.py +@@ -66,7 +66,7 @@ + self.cache.clear() + + def __len__(self) -> int: +- return self.length - 1 ++ return self.length + + def __contains__(self, key: object) -> bool: + return key in self.cache +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/validation/canaries/original-bug.sh b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/validation/openenv.json b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__07uxvexn/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/LICENSE.source b/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..611d35661f933a4469c941e6c97578c22673b4ab --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/LICENSE.source @@ -0,0 +1,7 @@ +Copyright (C) 2013 Markus Siemens + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/adapter.json b/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..9443dceb6031dc0df9d989b635eb0bd3ea64e3a0 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/adapter.json @@ -0,0 +1,127 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "2a75d35790f6496f754850af247239363d8226867be0988241601d82a0eefc59", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "0551e0806afd99add5cb7c6184a7e0b4813c16aa421c4031e64e7e3a27b44236", + "gold_patch_sha256": "10c58535f1b3050f02a47331f8a5739fc1b336556bbbe74886d2964a08259174", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "320bccf9e54f2a07950f3ddfcaff87182a8e6db08c4384e56ffff93160e87c01", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Tinydb10644a0e", + "profile_lines": [ + 1020, + 1023 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "upstream_repo": "msiemens/tinydb" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "48b0ea00c072a96f3fef198db1730cb71f880dc250922d3438ce7c3ea183de5c", + "partial_repair_wrongness_established": false, + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/msiemens__tinydb.10644a0e.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install 'pytest>=7.2,<8' 'pytest-cov>=4,<5'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "4318e4525086b9ab07b2269c7a6f1ff2003ad01a663b94f56e772d63655166be", + "pytest.ini": "2c2ccbf97dabef288fd402c4bb1ddba4d3baa35d1f903a3f5735633c1d504b7c" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "50798b793589760dc5c54aabe11323222b7ac62f", + "source_completion_sha256": "e55dadd28a6489338866e712ad9577f14cb2fddf83725cff1b0bfbac5a3db460", + "source_index_sha256": "a8bacb23b190ac8227d8d322773176a10ed65e6b16cccd869cb625a465522876", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:msiemens__tinydb.10644a0e.combine_file__1chu224v", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "278700580526dd378f18f40b641885ec78df63e1", + "instruction_sha256": "0f072016d0318660d1112b75a030ddf1626912aae9a5fa816124f708eabab48b", + "is_fork": true, + "learner_path": "tasks/5f17cf8ae56cc3cff752ae44/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "actual_upstream_url": "https://raw.githubusercontent.com/msiemens/tinydb/10644a0e07ad180c5b756aba272ee6b0dbd12df8/LICENSE", + "reviewed": true, + "sha256": "b0e2a2d39271e3d96b717d7be8235ac413d74797bf7f742f0801cfaad6c8c912", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/msiemens__tinydb.10644a0e/50798b793589760dc5c54aabe11323222b7ac62f/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "10644a0e07ad180c5b756aba272ee6b0dbd12df8", + "patch_sha256": "ef1c04ce000eaae745659d7933a3677b1160603031756ac6ab1e37ec686677e2", + "provenance_path": "tasks/5f17cf8ae56cc3cff752ae44/source-proof.json", + "repository_lineage": [ + "swesmith/msiemens__tinydb.10644a0e", + "msiemens/tinydb" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "50798b793589760dc5c54aabe11323222b7ac62f", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "385edc22ca70d2860c3c65088ded51e644eeb83a", + "source_kind": "mutation", + "source_repo": "swesmith/msiemens__tinydb.10644a0e", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "msiemens__tinydb.10644a0e.combine_file__1chu224v", + "task_sha256": "90652dc196cb2e5e657bce386a7a841332be5ddedcee0d78b6bed0e1651d7bd3", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "msiemens/tinydb", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/msiemens__tinydb.10644a0e", + "symlink_submodule_changes_supported": false, + "task_id": "msiemens__tinydb.10644a0e.combine_file__1chu224v", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "msiemens/tinydb" +} diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/dependency-setup.sh b/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..29ebee9df8beca1bfebc8b30cd7cb1dfc3cbf375 --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/dependency-setup.sh @@ -0,0 +1,17 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +/usr/bin/sha256sum --check <<'OPENENV_NATIVE_TEST_REQUIREMENT' +4318e4525086b9ab07b2269c7a6f1ff2003ad01a663b94f56e772d63655166be pyproject.toml +OPENENV_NATIVE_TEST_REQUIREMENT +python -m pip install -e . +python -m pip install 'pytest>=7.2,<8' 'pytest-cov>=4,<5' + +cat > /tmp/openenv-tinydb-yaml.txt <<'OPENENV_PYYAML_PIN' +PyYAML==6.0.3 --hash=sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b +OPENENV_PYYAML_PIN +python -m pip install --no-deps --only-binary=:all: --require-hashes --index-url https://pypi.org/simple -r /tmp/openenv-tinydb-yaml.txt +python -c 'import yaml; assert yaml.__version__ == "6.0.3"' diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/environment/Dockerfile b/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/instruction.md b/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1c6ab01e9cfd7b6b8e4227163cba2d959717dd1a --- /dev/null +++ b/tasks/msiemens__tinydb.10644a0e.combine_file__1chu224v/instruction.md @@ -0,0 +1,30 @@ +LRUCache returns incorrect length when empty + +#### Description + +The LRUCache class returns -1 when calling `len()` on an empty cache instead of 0. This causes issues with cache size validation and other operations that depend on the cache length. + +#### Steps/Code to Reproduce + +```python +from tinydb.utils import LRUCache + +# Create an empty cache +cache = LRUCache(capacity=5) +print(f"Length of empty cache: {len(cache)}") # Expected: 0, Actual: -1 + +# This also affects TinyDB operations +from tinydb import TinyDB +from tinydb.queries import where + +db = TinyDB(storage=TinyDB.default_storage_class) +table = db.table('test', cache_size=0) +table.insert({'int': 1}) +result = table.search(where('int') == 1) # Raises ValueError +``` + +The issue manifests when using zero cache size or when checking cache lengths, causing `ValueError: __len__() should return >= 0` errors. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access.